I have a bash script that uses a space-delimited string to keep track of all the possible valid arguments:
FRUITS="apple orange pear banana cherry"
I use a bash case statement because some of the arguments have special actions. The script can also loop on all valid arguments if called with no arguments
if ! [ "$1" = "" ]; then FRUITS=$*; fi
for fruit in $FRUITS; do
case "$fruit" in
apple)
action_1 ;;
cherry)
action_2 ;;
apple | orange | pear | banana | cherry)
default_action ;;
*)
echo "Invalid fruit"
exit 1 ;;
esac
done
Every time I add a new valid argument I have to add it in 2 places, e.g. if I add "kiwi":
FRUITS="apple orange pear banana cherry kiwi" # KIWI ADDED HERE
if ! [ "$1" = "" ]; then FRUITS=$*; fi
for fruit in $FRUITS; do
case "$fruit" in
apple)
action_1 ;;
cherry)
action_2 ;;
apple | orange | pear | banana | cherry | kiwi) # KIWI ADDED HERE
default_action ;;
*)
echo "Invalid fruit"
exit 1 ;;
esac
done
How can I use the $FRUITS variable instead of modifying the default_action pattern?
FRUITS="apple orange pear banana cherry kiwi"
if ! [ "$1" = "" ]; then FRUITS=$*; fi
for fruit in $FRUITS; do
case "$fruit" in
apple)
action_1 ;;
cherry)
action_2 ;;
$FRUITS) # THIS DOESN'T HAVE "|"s, SO DOESN'T WORK
default_action ;;
*)
echo "Invalid fruit"
exit 1 ;;
esac
done
$FRUITSand using$FRUITSas one of the cases means you could never reach the*case so your sample code is more confusing than it could be.appleandcherrydefined with 2 different actions in thecasestatement; is this a typo or is your intention to haveappleandcherryfire dual actions?IF .. ELSE .. FIas shown by @EdMorton answer on the last code block, would be simpler.