How can I do something like this in bash?

if "`command` returns any error";
    echo "Returned an error"
    echo "Proceed..."

migrated from Oct 16 '11 at 22:29

This question came from our site for professionals, academics, and students working within the systems development life cycle.

10 Answers 10

That's exactly what bash's if statement does:

if command ; then
    echo "Command succeeded"
    echo "Command failed"

Adding information from comments: you don't need to use the [ ... ] syntax in this case. [ is itself a command, very nearly equivalent to test. It's probably the most common command to use in an if, which can lead to the assumption that it's part of the shell's syntax. But if you want to test whether a command succeeded or not, use the command itself directly with if, as shown above.

  • 7
    Note that the semicolon is important. – Thorbjørn Ravn Andersen Oct 17 '11 at 7:37
  • 16
    Or you can just put then on a separate line. – l0b0 Oct 17 '11 at 9:00
  • 24
    @Joe: I think you mean if ! command ; then ... ; fi. [ is itself a command, and it's not needed in this case. – Keith Thompson Jan 13 '12 at 10:19
  • 14
    @Joe: My way also has the virtue of being correct. if [ ! command ] doesn't execute command; it treats command as a string and treats it as true because it has a non-zero length. [ is a synonym for the test command – Keith Thompson Jan 14 '12 at 9:36
  • 3
    Oops. You're correct. – Joe Jan 14 '12 at 10:09

For small things that you want to happen if a shell command works, you can use the && construct:

rm -rf somedir && trace_output "Removed the directory"

Similarly for small things that you want to happen when a shell command fails, you can use ||:

rm -rf somedir || exit_on_error "Failed to remove the directory"

Or both

rm -rf somedir && trace_output "Removed the directory" || exit_on_error "Failed to remove the directory"

It's probably unwise to do very much with these constructs, but they can on occasion make the flow of control a lot clearer.

  • 2
    They are shorter and (at least in some shells) faster. I shudder remembering a monster Ultrix installation script written with just these conditional constructions I once tried to decipher... – vonbrand Dec 27 '15 at 22:15

Check the value of $?, which contains the result of executing the most recent command/function:


echo "this will work"
if [ $RESULT -eq 0 ]; then
  echo success
  echo failed

if [ $RESULT == 0 ]; then
  echo success 2
  echo failed 2
  • 11
    While technically correct (and thus not warranting a downvote), it's not making use of Bash's if idiom. I prefer Keith Thompson's answer. – janmoesen Oct 17 '11 at 11:30
  • 10
    There are benefits to this idiom -- it preserves the return value. In all, I find this one to be more powerful, though more verbose. it's also easier to read. – taxilian Oct 7 '15 at 21:16
  • 2
    What is "Bash's if idiom"? – Nowaker Jun 27 '16 at 1:37
  • 2
    @Nowaker The fact that the sole purpose of if is to do this. The flow control conditions in Bash all examine $? behind the scenes; that's what they do. Explicitly examining its value should be unnecessary in the vast majority of cases, and is usually a beginner antipattern. – tripleee Nov 4 '16 at 12:34
  • @triplee so what is the correct pattern ? – danfromisrael Apr 17 at 9:02

This worked for me:

command && echo "OK" || echo "NOK"

if command succeeds, then echo "OK" is executed, and since it's successful, execution stops there. Otherwise, && is skipped, and echo "NOK" is executed.

  • 4
    If you want to do something if it fails, and preserve the exit code (to show in command prompt or test in a script), you can do this: command && echo "OK" || c=$?; echo "NOK"; $(exit $c) – Sam Hasler Jun 24 '14 at 15:57
  • 2
    @Sam-Hasler: shouldn't that be command && echo "OK" || (c=$?; echo "NOK"; (exit $c))? – jrw32982 Apr 1 '15 at 18:24
  • 8
    Also, if the echo "OK" part could itself fail, then this is better: command && (echo "OK"; exit 0) || (c=$?; echo "NOK"; (exit $c)) – jrw32982 Apr 1 '15 at 18:34
  • @jrw32982, Nice, I've used the former construction, but not the latter. – Sam Hasler Apr 2 '15 at 16:11
  • The real answer is in the comments, thanks all! – Joshua Pinter Oct 24 '17 at 20:13

It should be noted that and &&/|| type of approach deals with exit status returned by command we want to test( 0 on success ); however, some commands don't return a non-zero exit status if command failed or couldn't deal with input. This means that the usual if and &&/|| approaches won't work for those particular commands.

For instance, on Linux GNU file still exits with 0 if it received a non-existing file as argument and find couldn't locate the file user specified.

$ find . -name "not_existing_file"                                          
$ echo $?
$ file ./not_existing_file                                                  
./not_existing_file: cannot open `./not_existing_file' (No such file or directory)
$ echo $?

In such cases, one potential way we could handle the situation is by reading stderr/stdin messages, e.g. those that returned by file command, or parse output of the command like in find. For that purposes, case statement could be used.

$ file ./doesntexist  | while IFS= read -r output; do                                                                                                                  
> case "$output" in 
> *"No such file or directory"*) printf "%s\n" "This will show up if failed";;
> *) printf "%s\n" "This will show up if succeeded" ;;
> esac
> done
This will show up if failed

$ find . -name "doesn'texist" | if ! read IFS= out; then echo "File not found"; fi                                                                                     
File not found

if command-1 ; then
   echo "command-1 succeeded and now running from this block command-2"
   echo "command-1 failed and now running from this block command-3"

You can do this:

if ($( ping -c1 > /dev/null )) ; then
  echo "ping response succsess!!!"
  • 6
    That works but is convoluted. You're running ping in a subshell of a subshell, the output of ping is captured in view of running it as a command. But because the output is redirected to /dev/null that will always be the empty string. So you're running nothing in a subshell, which means the previous exit status (of the command substitution subshell, that is of ping) will be retained. Obviously, the correct way is if ping ...; then here. – Stéphane Chazelas Apr 1 '15 at 15:40

As noted elsewhere in this thread, the original question basically answers itself. Here is an illustration showing that if conditions may also be nested.

This example uses if to check if a file exists and if it is a regular file. If those conditions are true, then check whether or not it has a size greater than 0.


echo "Which error log are you checking today? "
read answer

if [ -f /opt/logs/$answer*.errors ]
        if [ -s /opt/logs/$answer*.errors ]
                echo "Content is present in the $answer error log file."
                echo "No errors are present in the $answer error log file."
        echo "$answer does not have an error log at this time."
  • 2
    That is what your answer does, but your answer does not address the question. – Jeff Schaller Dec 24 '15 at 2:47
  • @JeffSchaller, thank you for your note. I edited my post to include a reference to the question. – quartzinquartz Dec 27 '15 at 21:00

The most error prone I could come up with was:

  • First, get the value. Suppose you do something like:


Now, for not only this situation, but others you may face, consider:

defined variable:

$ AA=1 ; if (( "10#0${AA}" == 1 )) ; then echo yes ; else echo no ; fi

Answer: yes

$ AA=1 ; if (( "10#0${AA}" != 1 )) ; then echo yes ; else echo no ; fi

Answer: no

undefined variable:

$ AA=1 ; if (( "10#0${BB}" == 1 )) ; then echo yes ; else echo no ; fi

Answer: no

$ AA=1 ; if (( "10#0${BB}" != 1 )) ; then echo yes ; else echo no ; fi

Answer: yes

$ AA=1 ; if (( "10#0${BB}" == 0 )) ; then echo yes ; else echo no ; fi

Answer: yes

This prevents all kinds off errors.

You are probably aware of all the syntax, but here some tips:

  • Use quotes. Avoid a "blank" to be nothing.
  • The new modern notation for variables is ${variable}.
  • Adding a zero concatenated before your number also avoid "no number at all".
  • But wait, adding a zero makes the number become base-8. You will get an error like:
    • value too great for base (error token is "08") for numbers above 7. That is when 10# comes into play:
    • 10# forces the number to be base-10.

This could be done simply in this way as $? gives you the status of last command executed.

So it could be


... some command ...

if [ $? == 0 ] ; then
  echo '<the output message you want to display>'
  echo '<failure message>'
  • Downvote: This simply paraphrases an earlier answer which has rightfully received criticism for being unidiomatic. – tripleee Nov 4 '16 at 12:35

protected by Stephen Kitt Nov 22 '17 at 16:52

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?