bash中的命令行参数给出错误

时间:2014-03-17 12:32:58

标签: bash

我想编写一个bash脚本,其中一个命令行参数是A之类的字符串:

sh bash.sh file.in A

该脚本包含:

format=$2

if [$format = "A"]; then 
    ...
else 
    ...
fi

结果我收到了这个错误:

bash.sh: line 20: [A: command not found

2 个答案:

答案 0 :(得分:3)

试试这个:

#!/bin/bash

format="$2"

if [ "$format" = "A" ];then
   echo "Equal";
else
   echo "Not equal";
fi

<强>(OR)

if [[ $format = "A" ]];then
    ...
else
    ...
fi

答案 1 :(得分:3)

POSIX shell语法需要[]括号和表达式之间的空格。

试试这个:

if [ "$format" = "A" ]; then

...

else

...

fi

此外,如果可移植性不是问题,您可以使用更强大的

[[ "$format" == "A" ]]

其他信息:Is [[ ]] preferable over [ ] in bash scripts?