Reputation: 21453
I'm trying to write a script where I manipulate variables using options, but there are shortcuts if no option is specified. so for example, I have add
, show
, set
, and delete
, but if I don't specify any of those, then the input is interpreted to determine which operation to perform:
script key
is a shortcut for script show key
script key=value
is a shortcut for script set key=value
I'm written a case
statement for the options, but in the catchall, is it possible to say "go to case X"?:
case $1 in
add)
#blah;;
show)
#blah;;
set)
#blah;;
delete)
#blah;;
*)
if [[ $1 == *=* ]]; then
#go to case "set"
elif [[ $1 ]]; then
##go to case "show"
else
echo "FAILURE!!!"
exit 1
fi
esac
EDIT
I came up with:
case $1 in
add)
#blah;;
delete)
#blah;;
set|*=*)
#blah;;
show|*)
#blah;;
esac
Which almost works, but now if there is no last argument (i.e. i just execute script
) it will try to run script show
.
Upvotes: 3
Views: 847
Reputation: 785156
You can use "${1?arg needed}"
instead of $1
at the start of case
to fail the script when $1
is not supplied.
case "${1?arg needed}" in
add)
echo "add";;
delete)
echo "delete";;
set|*=*)
echo "set";;
show|*)
echo "show";;
esac
Testing this:
bash ./script
-bash: 1: arg needed
bash ./script foobar
show
bash ./script abc=123
set
Upvotes: 2
Reputation: 74615
I would suggest structuring your code like this:
if [[ -z $1 ]]; then
echo "FAILURE!!!"
exit 1
fi
case $1 in
add)
#blah;;
set|*=*)
#blah;;
delete)
#blah;;
show|*)
#blah;;
esac
i.e. fail before hitting the case
statement and use |
to combine the patterns for each case.
Upvotes: 4
Reputation: 364
try:
case $1 in
add)
#blah;;
show|*)
#blah;;
set|*=*)
#blah;;
delete)
#blah;;
*)
echo "FAILURE!!!"
exit 1
esac
Upvotes: -2