【发布时间】:2021-11-26 02:25:57
【问题描述】:
我编写了一个脚本来自动重新启动我的网络服务器,进行某些检查,然后将带有时间戳的消息打印到日志文件中。因为我从不同的地方调用这个文件(cron 作业,当我更新我的站点时,手动等等),我想有一种方法可以根据我调用它的原因将不同的消息打印到日志文件中。我决定使用选项来执行此操作,并且还决定添加帮助、详细和测试选项。
选项部分的代码:
# initializing variables
test=false
help=false
verbose=false
modeCount=0
msg="restarted"
# looking at options
while getopts ":aeghmstv" option; do
case $option in
a) # Automatic restart
((modeCount+=1))
msg="$msg automatically";;
e) # Error-triggered restart
((modeCount+=1))
msg="$msg due to an error";;
g) # Pull-triggered restart
((modeCount+=1))
msg="$msg on git pull";;
h) # Help
help=true;;
m) # Manual restart
((modeCount+=1))
msg="$msg manually";;
s) # Startup-triggered restart
((modeCount+=1))
msg="$msg on startup";;
t) # Testing mode
test=true;;
v) # Verbose mode
verbose=true;;
\?) # Invalid option
echo "Error: Invalid option; use the h option for help"
exit;;
esac
done
# checking for input errors
if [ "$help" == true ]; then
if [ $modeCount -gt 0 ] || [ "$test" == true ] || [ "$verbose" == true ]; then
echo "Error: No other options can be used with h; use the h option for help"
else
help
fi
exit
fi
if [ $modeCount != 1 ]; then
echo "Error: 1 log message option must be used; use the h option for help"
exit
fi
但是,另外,我希望能够将字符串作为位置参数传递,以便将其他信息添加到我的日志文件中。 例如,如果我运行:
./restart.sh -a
它记录如下内容:
2021-10-04T00:00:04 restarted automatically
但我希望能够更改它以便我可以(可选)运行:
./restart.sh -a "daily restart"
它会改为记录:
2021-10-04T00:00:04 restarted automatically: daily restart
我发现 this question 关于混合 getops 和参数,但如果我希望参数是可选的,我不知道该怎么做。
一旦我得到那个字符串,就很容易简单地添加如下一行:
msg="$msg: $info"
但我不确定如何验证这样的参数是否存在,然后将其存储在变量中。
PS:无论参数/选项的顺序如何,我也希望它能够工作。例如,我想要:
./restart.sh -a "daily restart"
and
./restart.sh "daily restart" -a
以同样的方式工作。
【问题讨论】:
-
getopts完成后,位置参数都是其后的非选项参数。
标签: bash shell parameters options