2016-02-25 67 views
-1

我正試圖實現Unix的which函數,但不斷收到語法錯誤,我認爲是合法的?這是我的實現:實現shell中的哪個函數

IFS=":" 
x=false 

for i in $* 
do 
    for j in $PATH 
    do 
     if [ -x "${j}/$i" ];then 
      echo $j/$i 
      x=true 
      break 
     fi 
    done 
    if [ $x == false ]; then 
     echo my_which $i not found in --$PATH-- 

    fi 
    x=false 

done 

我不斷收到以下錯誤

$ bash which.sh 
: command not found: 
'which.sh: line 5: syntax error near unexpected token `do 
'which.sh: line 5: `do 
+0

...另外,'=='不是POSIX字符串比較運算符 - 它是'=';有些實現可能會接受'==',但標準並不要求它們這樣做。請參閱http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html –

+0

...並始終引用您的擴展。 'echo「my_which $我找不到 - $ PATH - 」' –

+2

複製粘貼您發佈的代碼並再次測試。 –

回答

1

你的腳本有DOS換行符。使用dos2unix來轉換它,或者在可以爲你做轉換的編輯器中打開它(在vim中,你將運行:set fileformat=unix,然後使用:w保存)。

$ bash which.sh 
: command not found: 
'which.sh: line 5: syntax error near unexpected token `do 
'which.sh: line 5: `do 

查看' s在這些行的開頭?這些應該在該行的末端處。

發生了什麼事,但是,那是你do■找他們之後隱藏$'\r'性格,這將光標回行的開頭。因此,而不是看到do爲有效的令牌,或者正確打印

# this is the error you would get if your "do" were really a "do", but it were still 
# ...somehow bad syntax. 
syntax error near unexpected token `do' 

...我們得到了...

# this is the error you get when your "do" is really a $'do\r' 
'yntax error near unexpected token `do 

...因爲回車是do和坐在之間'

+0

非常感謝!使用Vim和保存工作。:-) – unicornication