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

2 Answers 2

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 yesterday

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 yesterday

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.