运行bash脚本时出现"0: command not found"错误

分享于 

2分钟阅读

ubuntu

  繁體

问题:

这是脚本:


echo "please enter any number"


read n


a= $(($n % 2))


if [ $a -eq 0 ]; then


 echo "EVEN"


else


 echo "ODD"


fi



这是脚本的输出:


$ source first.sh 


please enter any number


2


0: command not found


ODD



错误的原因是什么?


答案1:


$ bash -vx first.sh


bash -vx first.sh


echo "please enter any number"


+ echo 'please enter any number'


please enter any number


read n


+ read n


4


a= $(($n % 2)) 


+ a= <======As a comment mentioned, a space causes problems


+ 0


first.sh: line 3: 0: command not found


if [ $a -eq 0 ]; then


 echo "EVEN"


else


 echo "ODD"


fi


+ '[' -eq 0 ']'


first.sh: line 4: [: -eq: unary operator expected


+ echo ODD


ODD




答案2:

问题出在a=后的空格,变量赋值应该是a=$(($n %2))

通常,空格在Bash脚本中很重要,

  • 未用空格分隔的内容被认为是一个"单词"

  • 用一个或多个空格字符分隔的事物被视为两个(或多个)单词。

  • 如预期。

    a= $(($n % 2))0: command not found1: command not found

    [ $a -eq 0 ]

    
    [: -eq: unary operator expected
    
    
    
    


    COM  COMM  Comma  BASH  bash-script