如何检查-h
属性是否已传递到shell脚本中?我想在用户调用myscript.sh -h
时显示一条帮助消息。
发布于 2011-03-29 23:11:00
shell脚本的第一个参数可以作为变量$1
使用,因此最简单的实现是
if [ "$1" == "-h" ]; then
echo "Usage: `basename $0` [somestuff]"
exit 0
fi
但是阿努巴瓦说了什么。
发布于 2015-06-14 22:03:41
下面是我用它来启动VNC服务器的一部分
#!/bin/bash
start() {
echo "Starting vnc server with $resolution on Display $display"
#your execute command here mine is below
#vncserver :$display -geometry $resolution
}
stop() {
echo "Killing vncserver on display $display"
#vncserver -kill :$display
}
#########################
# The command line help #
#########################
display_help() {
echo "Usage: $0 [option...] {start|stop|restart}" >&2
echo
echo " -r, --resolution run with the given resolution WxH"
echo " -d, --display Set on which display to host on "
echo
# echo some stuff here for the -a or --add-options
exit 1
}
################################
# Check if parameters options #
# are given on the commandline #
################################
while :
do
case "$1" in
-r | --resolution)
if [ $# -ne 0 ]; then
resolution="$2" # You may want to check validity of $2
fi
shift 2
;;
-h | --help)
display_help # Call your function
exit 0
;;
-d | --display)
display="$2"
shift 2
;;
-a | --add-options)
# do something here call function
# and write it in your help function display_help()
shift 2
;;
--) # End of all options
shift
break
;;
-*)
echo "Error: Unknown option: $1" >&2
## or call function display_help
exit 1
;;
*) # No more options
break
;;
esac
done
######################
# Check if parameter #
# is set too execute #
######################
case "$1" in
start)
start # calling function start()
;;
stop)
stop # calling function stop()
;;
restart)
stop # calling function stop()
start # calling function start()
;;
*)
# echo "Usage: $0 {start|stop|restart}" >&2
display_help
exit 1
;;
esac
我把start、stop、restart放在一个单独的情况下,这有点奇怪,但它应该可以工作
发布于 2011-03-29 23:08:41
最好使用bash的getopt工具。请查看此问答以获取更多帮助:Using getopts in bash shell script to get long and short command line options
https://stackoverflow.com/questions/5474732
复制相似问题