在shell中实现哪个函数

时间:2016-02-25 23:10:18

标签: bash shell unix

我正在尝试实现Unix的mysite.com/example/something 函数,但是在我(认为)合法的情况下继续得到语法错误?这是我的实施:

which

我一直收到以下错误

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 

1 个答案:

答案 0 :(得分: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

请参阅这些行开头的'?这些应该位于该行的 end

然而,发生的事情是你的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'之间。