2

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?

10

You can group command in curly braces:

[ "$#" -ne 3 ] || { command; exit; }

{ list; } causes lists command run in current shell context, not in subshell.

Read more about bash Grouping commands

3

Try this

f() { [ "$#" -ne 3 ] && { command ; exit; }; }; f 1 2 3

Then

f() { [ "$#" -ne 3 ] && { command ; exit; }; }; f 1 2
  • what are 1 2 3 ? – holasz Aug 5 '14 at 11:21
  • 1
    Those are arguments passed to the function f. The { command; exit ; }... runs only if there are less than number of arguments required. – Valentin Bajrami Aug 5 '14 at 11:25
  • 1
    @val0x00ff: -ne meaning not equal, not less than. – cuonglm Aug 5 '14 at 11:58
  • @Gnouc nice catch. It will indeed succeed only if there are 3 arguments passed, otherwise it fails. – Valentin Bajrami Aug 5 '14 at 12:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.