Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
1  
There is more here: mywiki.wooledge.org/BashFAQ/… –  val0x00ff Aug 5 at 10:57
    
Are you entering an obfuscated shell code contest? If so you'll have to do better than that. If not, write what you mean: use if. –  Gilles Aug 5 at 21:21

2 Answers 2

up vote 8 down vote accepted

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

share|improve this answer

Try this

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

Then

f() { [ "$#" -ne 3 ] && { command ; exit; }; }; f 1 2
share|improve this answer
    
what are 1 2 3 ? –  holasz Aug 5 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. –  val0x00ff Aug 5 at 11:25
1  
@val0x00ff: -ne meaning not equal, not less than. –  Gnouc Aug 5 at 11:58
    
@Gnouc nice catch. It will indeed succeed only if there are 3 arguments passed, otherwise it fails. –  val0x00ff Aug 5 at 12:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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