shell 編程中空格的使用方法

字號:


    1.定義變量時, =號的兩邊不可以留空格.
    eg:
    gender=femal————right
    gender =femal———–wrong
    gender= femal———–wrong
    2.條件測試語句 [ 符號的兩邊都要留空格.
    eg:
    if [ $gender = femal ]; then——-right.
    echo “you are femal”;
    fi
    if[ $gender...-----------------------wrong
    if [$gender...----------------------wrong.
    3.條件測試的內(nèi)容,如果是字符串比較的話, 比較符號兩邊要留空格!
    eg:
    if [ $gender = femal ]; then——-right.
    if [ $gender= femal ]; then——–wrong.
    if [ $gender=femal ]; then———wrong.
    4.如果if 和 then寫在同一行, 那么,注意, then的前面要跟上 ; 號.如果 then 換行寫, 那么也沒問題.
    eg:
    if [ $gender = femal ]; then——-right.
    if [ $gender = femal ]
    then——————————-right.
    if [ $gender = femal ] then——-wrong. then前面少了 ; 號.
    提示出錯信息:
    syntax error near unexpected token then
    同理,還有很多出錯信息 比如
    syntax error near unexpected token fi 等都是這樣引起的.
    5.if 后面一定要跟上 then. 同理
    elif 后面一定要跟上 then.
    不然提示出錯信息:
    syntax error near unexpected token else
    1)if 語句后面需要跟著then,同時前面要有分號;
    2) 空格非常重要,shell 會認為空格前的為一個命令,如果a=3 認為是賦值操作,如果寫成a = 3,那么就會認為a為一個命令 this=`ls -l |grep ‘^-' | wc -l `
    3) 操作符之間要用空格分開 ,如 test ! -d $1,其中的!和-d就要用空格分開
    空格是命令解析中的重要分隔符
    6. 命令和其后的參數(shù)或?qū)ο笾g一定要有空格
    if [ -x"~/Workspace/shell/a.sh" ];then
    只有 -x 后有空格才表示緊跟其后的字符串是否指向一個可執(zhí)行的文件名,否則就成了測試 -x"~/Workspace/shell/a.sh" 這個字符串是不是空。
    7.取變量值的符號'$'和后邊的變量或括號不能有空格