在 bash 脚本的命令行选项前使用可选参数
Use optional argument before options on command line in a bash script
我有一个脚本 myscript
应该执行以下操作:
- 运行 本身:
myscript
- 运行 带有参数:
myscript myarg
- 运行 选项:
myscript -a 1 -b 2 -c 3 ...
- 运行 带有参数和选项:
myscript myarg -a 1 -b 2 -c 3 ...
我无法让 4. 工作,似乎在选项前使用参数(我从 getopts
中获取)会干扰 getopts
处理所有内容的方式。
我使用的代码基本上是这样的:
while getopts "a:b:c:" opt; do
case ${opt} in
a)
var_a=$OPTARG
;;
... more options here
esac
done
if [ ! -z "" ] && [[ ! "" =~ ^- ]]; then
... do stuff with first argument - if it's there and it's not just an option
fi
如果有解决这个问题的简单方法,我将不胜感激!
你可以在脚本的最后if
中使用shift
(大意已经存在,你写"do stuff with first argument - if it's there and it's not just an option")。
我有一个脚本 myscript
应该执行以下操作:
- 运行 本身:
myscript
- 运行 带有参数:
myscript myarg
- 运行 选项:
myscript -a 1 -b 2 -c 3 ...
- 运行 带有参数和选项:
myscript myarg -a 1 -b 2 -c 3 ...
我无法让 4. 工作,似乎在选项前使用参数(我从 getopts
中获取)会干扰 getopts
处理所有内容的方式。
我使用的代码基本上是这样的:
while getopts "a:b:c:" opt; do
case ${opt} in
a)
var_a=$OPTARG
;;
... more options here
esac
done
if [ ! -z "" ] && [[ ! "" =~ ^- ]]; then
... do stuff with first argument - if it's there and it's not just an option
fi
如果有解决这个问题的简单方法,我将不胜感激!
你可以在脚本的最后if
中使用shift
(大意已经存在,你写"do stuff with first argument - if it's there and it's not just an option")。