Bash脚本-如何使选项优先级比其他选项更重要
我的脚本中有优先级问题。 例如,当我调用我的脚本。/script-q-h时,它应该返回h选项,该选项应该比其他选项具有更重要的优先级。我的代码如下:Bash脚本-如何使选项优先级比其他选项更重要,bash,Bash,我的脚本中有优先级问题。 例如,当我调用我的脚本。/script-q-h时,它应该返回h选项,该选项应该比其他选项具有更重要的优先级。我的代码如下: #!/bin/bash function usage { echo "Echoing login, name, surname of the invoker where: -h help -q quit(don't proceed script)" } function invalid { echo "Invalid argu
#!/bin/bash
function usage
{
echo "Echoing login, name, surname of the invoker
where:
-h help
-q quit(don't proceed script)"
}
function invalid
{
echo "Invalid argument!
"
usage
}
while [ "$1" != "" ]; do
case $1 in
-h | --help ) usage
exit
;;
-q | --quit ) exit
;;
* ) invalid
exit 1
esac
shift
done
echo $USER
getent passwd $USER | cut -d: -f5 | cut -d, -f1
在您的
案例
检查中,只需设置变量(例如opt_h=1
或opt_q=1
)
然后按照您想要的顺序检查变量:
if [ -n "$opt_h" ]; then
usage
exit
fi
if [ -n "$opt_q" ]; then
exit
fi
我的方法是在case)块中设置一个变量。 i、 e
无论如何,你为什么需要选择退出?对于大多数交互式工具来说,完成后退出并不是可选的,它只是一个家庭作业。我还需要在tcsh中执行相同的脚本,但不知道如何执行。例如,tcsh似乎没有函数。@triplee A-q选项的位置可能是某些服务的管理工具,其中q可以被视为关闭服务。或者启动服务,读取输入文件并继续运行新输入文件的轮询,除非您提供了-q选项。或者
做很多事情;阅读选项;当您不退出时,请执行更多操作。
我认为OP在回显“Invalid arg”
之后需要一个DOHELP=true
。当然,这个问题是关于如何优先选择选项,而不是好的脚本设计。
while [ "$1" != "" ]; do
case $1 in
-h | --help ) DOHELP=true
;;
-q | --quit ) DOQUIT=true
;;
* ) echo "Invalid arg"
exit 1
esac
shift
done
if [ -n "$DOHELP" ]; then
usage
exit 0
fi
if [ -n "$DOQUIT" ]; then
exit 0
fi