Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

This is my first time attempting to write a long bash script to manage a server I run, and when using "set -ex" the script exits when umount fails. I thought my if statement would catch it but the script exits before echo is fired.

What am I overlooking here?

umount $MOUNTPATH
if [[ $? -ne 0 ]];
then
  /bin/echo "Failed to unmount!  Already unmounted?"
fi
share|improve this question
add comment

2 Answers 2

up vote 3 down vote accepted

set -e will make the shell exit as soon as a command fails. That is, as soon as the unmount command finishes. The if cannot catch it, since the script exits before it even gets to the if. You can fix this by putting the unmount command in the if condition (negated with ! to make it run the then clause if the unmount fails, rather than if it succeeds):

if ! unmount $MOUNTPATH; then
    /bin/echo "Failed to unmount!  Already unmounted?"
fi
share|improve this answer
    
Ah ok, I did not realize this either. Thank you. –  Jeff Nov 17 '12 at 3:05
add comment

The issue is that you have a semi-colon after your if statement.

umount $MOUNTPATH
if [[ $? -ne 0 ]]
then
  /bin/echo "Failed to unmount!  Already unmounted?"
fi

That should fix it.

Sources: http://bash.cyberciti.biz/guide/If_structures_to_execute_code_based_on_a_condition

share|improve this answer
    
I'll have to read up more, I thought the semi-colon was necessary. I see now that's only if i put then on the same line. Thank you. –  Jeff Nov 17 '12 at 2:57
    
Added a link to for a pretty good tutorial on conditionals in bash –  prateek61 Nov 17 '12 at 3:00
    
I am also going to point out that Gordon Davisson's answer is probably more correct than mine. I would try that as it seems neater. –  prateek61 Nov 17 '12 at 3:05
add comment

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.