这是一个初学者问题,我已经检查了Check existence of input argument in a Bash shell script,但它并没有完全解释我想要做什么。
gcc -Wall cx17.$1.c -o cx17.$1
if [ -z "$1" ]
then
echo "No argument supplied"
else if [ -z "$2"]
then
echo "Data file is missing!!"
else if [ -z "$3"]
then
./cx17.$1 $2 > ./cx17.$1.$2
else
./cx17.$1 $2 $3 > ./cx17.$1.$2
fi
所以你理解这个非常基本的用例,根据参数(如果有1,2或3),脚本将执行不同的任务。
我知道这很简单,这就是为什么我认为我错过了一些明显的东西。
感谢您的帮助
我验证的回答给了我一些错误但引导我找到正确的东西:
if [ -z "$1" ]; then
echo 'No argument supplied';
elif [ -z "$2" ]; then
echo 'Data file is missing!!';
elif [ -z "$3" ]; then
./cx17.$1 $2 >./cx17.$1.$2;
else
./cx17.$1 $2 $3 >./cx17.$1.$2;
fi;
答案 0 :(得分:3)
将else if
替换为elif
:
if [[ -z "$1" ]]; then
echo 'No argument supplied';
elif [[ -z "$2" ]]; then
echo 'Data file is missing!!';
elif [[ -z "$3" ]]; then
"./cx17.$1" "$2" >"./cx17.$1.$2";
else
"./cx17.$1" "$2" "$3" >"./cx17.$1.$2";
fi;
其他建议:
[[
代替[
,因为前者更强大,并且保持一致性很好。答案 1 :(得分:1)
您可以使用if
构造完全省略${var:?msg}
语句,如果给定变量没有非空值,它将退出脚本。
: ${1:?No argument given}
: ${2:?Data file is missing!}
# $1 and $2 guaranteed to be non-null; the program
# will receive 1 or 2 arguments, depending on how many
# arguments are present in $@
./cx17."$1" "${@:2:2}" > "./cx17.$1.$2"