我有一个Bash脚本,我需要传递一定数量的参数才能使它工作.
./upload.sh $ARG1 $ARG2 $ARG3
假设2个必填字段是ARG1和ARG2,
ARG1和3不是空的.
我认为脚本会运行并认为它有2个强制参数,有没有办法检测到ARG2丢失/为空?我需要返回退出1而不是退出0.
这是一些脚本
RESOURCE=$1
CONTAINER=$2
APP_NAME=$3
if [[ -z $RESOURCE || -z $CONTAINER ]];
then
echo `date`" - Missing mandatory arguments: resource and container. "
echo `date`" - Usage: ./upload.sh [resource] [container] [appname] . "
exit 1
fi
Run Code Online (Sandbox Code Playgroud)
提前致谢,
阿兰
我总是使用一个小函数来检查所有参数:
process_arguments() {
while [ -n "$1" ]
do
case $1 in
-h|--help) echo "some usage details"; exit 1;;
-x) do_something; shift; break;;
-y) do_something_else; shift; break;;
*) echo "some usage details"; exit 1;;
esac
echo $1; shift
done
}
Run Code Online (Sandbox Code Playgroud)
这样,如果您错过任何内容,将显示正确的使用详细信息,脚本将退出。否则,您可以按任意顺序输入参数。当你的脚本启动时,只需调用
process_arguments "$@"
Run Code Online (Sandbox Code Playgroud)
你应该已经准备好了。
有没有办法检测 ARG2 丢失/为空?
不。根据您传递参数的方式,这些参数将被解释为参数 1 和 2。
你也可以说:
./upload.sh "$ARG1" "$ARG2" "$ARG3"
Run Code Online (Sandbox Code Playgroud)
为了使 bash 正确解释参数,无论这些参数是否为空。
例子:
$ cat file
[ -z $1 ] && echo "Arg 1 missing"
[ -z $2 ] && echo "Arg 2 missing"
[ -z $3 ] && echo "Arg 3 missing"
$ bash file "$HOME" "$FOOBAR" "$USER"
Arg 2 missing
Run Code Online (Sandbox Code Playgroud)
(在上面的示例中该变量FOOBAR
未定义。)