我尝试过什么。
#!/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