假设我有一个脚本,您传递了命令行选项--stable
和--unstable
。传递--unstable
时,用户还应该能够传递--harmony
,这会启用仅在不稳定版本中出现的功能,例如
./script --unstable --harmony
但是,如果用户执行以下操作会怎么样:
./script --stable --harmony
我应该抛出错误并停止执行吗?或者我应该忽略--harmony
标志?
答案 0 :(得分:1)
您可以打印"警告"消息说该选项无效,您将忽略它。我看到有几十个脚本在做那个
答案 1 :(得分:1)
您可以使用仅限bash =~
运算符轻松完成此操作,以测试包含stable
和harmony
的所有参数:
#!/bin/bash
[[ "$@" =~ "stable" ]] && [[ "$@" =~ "harmony" ]] && {
printf "\nerror: incompatible arguments provided.\n"
printf " arguments 'stable' and 'harmony' are mutually exclusive.\n\n"
exit 1
}
printf "\n Only compatible arguments passed.\n\n"
exit 0
<强>用法:强>
$ bash stblharm.sh --stable --harmony
error: incompatible arguments provided.
arguments 'stable' and 'harmony' are mutually exclusive.
$ bash stblharm.sh --stable --something_else
Only compatible arguments passed.