what I tried.
#!/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
What I am trying to do:
in terminal, the following 2 command:
bash /home/jian/Desktop/pgdev/test1.sh -s
bash /home/jian/Desktop/pgdev/test1.sh -r
do not print out aftercase
.
references: How to use getopts in bash
https://stackoverflow.com/questions/1378274/in-a-bash-script-how-can-i-exit-the-entire-script-if-a-certain-condition-occurs
exit
in the case statement. However if you do so there is no point in defining the functions as the definitions will be lost when the shell exits. Normally you would put the main part of your script where it says after_case, using the yell die try statements. What are you actually trying to do? – icarus Oct 12 '23 at 19:20r
and/ors
as options. – Henrik supports the community Oct 12 '23 at 21:30yell
/die
/try
functions multiple times? They don't seem to change, so just put the once at the top of the script. Or do you think that defining thetry
function liketry() { "$@" || die "cannot $*"; }
actually also invokes it? – muru Oct 13 '23 at 02:28try
ordie
as a command. – muru Oct 13 '23 at 02:39func() { ... }
is a function definition, it creates the function. It doesn't run it. The command to exit the script isexit
, the same you have there in the last branch of thecase
. – ilkkachu Oct 13 '23 at 05:29