![如何使用 bash 脚本中的 getopts 选项立即退出](https://linux22.com/image/225407/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%20bash%20%E8%84%9A%E6%9C%AC%E4%B8%AD%E7%9A%84%20getopts%20%E9%80%89%E9%A1%B9%E7%AB%8B%E5%8D%B3%E9%80%80%E5%87%BA.png)
我尝试过什么。
#!/bin/bash
# set -e
echo hello
while getopts sr o; do
case $o in
s)
echo "no"
yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }
;;
r)
echo "yes"
yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }
;;
\?) exit 3;; #invalid option
esac
done
echo after_case
我想做的:在终端中,执行以下 2 个命令:
bash /home/jian/Desktop/pgdev/test1.sh -s
bash /home/jian/Desktop/pgdev/test1.sh -r
不打印aftercase
。
参考:如何在 bash 中使用 getopts
https://stackoverflow.com/questions/1378274/in-a-bash-script-how-can-i-exit-the-entire-script-if-a-certain-condition-occurrs
答案1
你可以做这样的事情。您的 yell()、die() 和 try() 函数可以写在脚本的顶部。
#!/usr/bin/env bash
#
usage() {
echo "usage: <command> options:<s|r|o>"
echo "-s s_value -r r_value -o o_value"
}
yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }
no_args="true"
while getopts s:r:o: flag; do
case "${flag}" in
s) yell
die
try
;;
r) resource=${OPTARG} ;;
o) other=${OPTARG} ;;
*)
usage
exit
;;
esac
no_args="false"
done
[[ "$no_args" == "true" ]] && {
usage
exit 1
}
## other things to do