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.

It's a simple question of best pratices: Which should I use?

Option 1

ping -c1 "$host"

if [[ $? -eq 0 ]] ; then
   command
else
   command
fi

Option 2

if ping -c1 "$host" ; then
   command
else
   command
fi

I know this is a simple command, but if it grows big, the difference might be significant.

share|improve this question

3 Answers 3

It's a matter of preference, but the second form may be safer if you intend to add a set -e: this form will still work as expected, while with the first form, the script will end immediately if ping fails (returns with a non-zero exit status).

Note: the operator is -eq, not eq.

share|improve this answer
    
Just typo the operator. But thx, I prefer the second one :D –  jonatas.baldin Aug 30 at 21:42

Option 2 is only an option when you only care about the difference between success and failure. If you need to differentiate between different non-zero exit statuses, then option 1 is necessary.

some-command arg1 arg2
exit_status=$?
if [[ $exit_status -eq 0 ]]; then
   # ...
elif [[ $exit_status -eq 1 ]]; then
   # ...
elif [[ $exit status -eq 42 ]]; then
   # ...
else
   # ...
fi

(You need to save $? as exit_status because $? will be reset by the first [[ ... ]] command; if it fails, the first elif wouldn't test the same value for $? again.)

Well, not quite necessary. A third option is to use a case statement, which can eliminate the need for saving $? if you don't need to refer to its value again.

some-command arg1 arg2
case $? in
   0) # ...
   ;;
   1) # ...
   ;;
   42) # ...
   ;;
   *) # ...
   ;;
 esac
share|improve this answer

You can use the following Bash idiom which may seem unreadable but is quite common in practice.

ping -c1 "$host" && command_success || command_failure
share|improve this answer
    
Yeah, know that. Can use the || also! –  jonatas.baldin Aug 31 at 5:47

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.