2016-02-25 68 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