While writing a simple shell tool, I found a piece where I don't know how to get it to work.
[ "$#" -ne 3 ] || echo "wrong number of arguments" && exit
The above works as intended because it's hard to conceive conditions where echo could fail. But what if I replaced echo with a command that can fail, and still execute exit
nevertheless?
This won't work, because exit
quits the shell spawned with ( )
and not the main one:
[ "$#" -ne 3 ] && ( command ; exit )
This will exit always:
[ "$#" -ne 3 ] && command ; exit
I could use the verbose syntax:
if [ "$#" -ne 3 ] ; then
command
exit
fi
but if I don't want to engage if
and keep the syntax terse – how can I string conditional execution of commands, including exit
like that?
Best Answer
You can group command in curly braces:
{ list; }
causes lists command run in current shell context, not in subshell.Read more about
bash
Grouping commands