On the command line no one can hear you screen. Or can they?

3 May 2012   2 comments   Linux

Mind that age!

This blog post is 10 years old! Most likely, its content is outdated. Especially if it's technical.

This is how you check if a command (with or without any output) exited successfully or if it exited with something other than 0, in bash:

if [ "$WORKED" != 0 ]; then
  echo "FAILED"
  echo "WORKED"

But how do you inspect this on the command line? I actually don't know, until it hit me. The simplest possible solution:

$ ./someprogram && echo worked || echo failed

What a great low-tech solution. I just works. If you're on OSX, you can nerd it up a bit more:

$ ./someprogram && say worked || say failed



I just wanted to add that within bash, if tests work on programs too so you can also write it as:

if ./someprogram
    echo "WORKED"
    echo "FAILED"


if ! ./someprogram
    echo "FAILED"
    echo "WORKED"

This works well for many circumstances. I find a commonly used one I use is grep -q, for example:

if ./run_command | grep -q 'some regex'

Additionally, though this isn't portable (meaning it may not work with /bin/sh or shells other then /bin/bash) but [[ and ]] is a much more stable test method then [ and ] in bash and additionally [[ and ]] allow for multiple tests using && and || so you could write:

if [[ "$test1" == "abc" || "$test2" == "def" ]]

Also, this isn't portable but works on bash, you can do arithmetic testing using (( and )), i.e.:

if (($WORKED == 0))

This only works on integers (whole numbers) which you can ensure by declaring your variable as an integer only and cannot contain letter, punctuation or anything except a whole number:

declare -i WORKED=$?

If you pull up the man page for bash you can do a search for "[[ expression ]]", "((expression))" and "ARITHMETIC EVALUATION" (sans the quotes) and from within bash you can run:
help [[
help '(('
help declare
help test # help test refers to [ and ] but all the checks are equally valid in [[ and ]]

P.S. It's strongly cautioned to be very careful when performing tests like "my_program && action1 || action2". In this instance, if action1 fails then action2 will be executed even though you only wanted to perform action2 if my_program had failed so action1 must be incredibly simple that it cannot fail. Additionally, chaining a bunch of actions together outside of an if clause such as "my_program && do_this && this && and_this || fail with_this" where you want do_this, this and and_this to all be executed if my_program exits without error is a recipe for disaster. You're basically creating a condition that adds to a lot of uncertainty and can become much more likely to fail. Either keep it very very simple or put it in a if/else/then clause.

Selena Deckelmann

Or you can have your prompt tell you:

export PS1="\u@\h:\W #\! \A \`if [ \$? == 0 ]; then echo \:\); else echo \:\(; fi\` "

Your email will never ever be published.

Related posts