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.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to do something like this:

if cmd1 && cmd2
echo success
else
echo epic fail
fi

How should I do it?

share|improve this question
    
You're just missing the "then" keyword before the "echo success" command. – glenn jackman Jun 22 '11 at 10:29
3  
Hmmm; your pseudocode seems to ask a different question than the one in your title..... – mattdm Jun 22 '11 at 14:43
    
Good resource for some shell scripting exit conditions pixelbeat.org/programming/shell_script_mistakes.html – Flashman Jun 22 '11 at 15:16
up vote 38 down vote accepted

These should do what you need:

cmd1 && cmd2 && echo success || echo epic fail

or

if cmd1 && cmd2; then
    echo success
else
    echo epic fail
fi
share|improve this answer
    
This works, but I'm confused why || doesn't look at the output of the first echo command. – mlissner Aug 19 '15 at 21:32
    
@mlissner, the if else expects to exit codes, 0 if the command where launched and 1 if where errors. Do not read at the output. Just try whoami && whoami && echo success || echo epic fail and now whoami && whoareyou && echo success || echo epic fail. I cant figure out what you mean by "doesn't look at the output of the first echo command" – erm3nda Feb 9 at 14:41

Petr Uzel is spot on but you can also play with the magic $?.

$? holds the exit code from the last command executed, and if you use this you can write your scripts quite flexible.

This questions touches this topic a little bit, Best practice to use $? in bash? .

cmd1 
if [ "$?" -eq "0" ]
then
  echo "ok"
else
  echo "Fail"
fi

Then you also can react to different exit codes and do different things if you like.

share|improve this answer

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.