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.
    #!/bin/sh

function checkExit(){
    if test "$?" != "0"; then
      echo Command $1 exited with abnormal status
      exit 1;
    else echo $?
    fi
}

function echoThenRun () { # echo and then run the command
  echo $1
  $1
  ret=$?
  echo $ret
  return $ret
}
file=test_file
echo > $file
echoThenRun "test -f $file"
checkExit $file
echo "all right!"

The output of executing the script:

$  ~/Downloads/test.sh 
test -f test_file
0
1 # why 1 here??
all right!
share|improve this question
add comment

2 Answers 2

up vote 5 down vote accepted

There's a simpler way of what you're doing. If you use set -x, the script will automatically echo each line before it's executed.

Also, ss soon as you execute another command, $? is replaced with the exit code of that command.

You'll have to back it up to a variable if you're going to be doing anything with it other than a quick test-and-forget. The [ is actually a program that has its own exit code.

For example:

set -x # make sure the command echos
execute some command...
result="$?"
set +x # undo command echoing
if [ "$result" -ne 0 ]; then
    echo "Your command exited with non-zero status $result"
fi
share|improve this answer
add comment

Looks to me like the command test "$?" != "0" ends up setting $? to 1. The value $? gets used in the arguments to test. test sets $? to a non-zero value because "0" is lexically equal to "0". The "!=" makes test return non-zero.

share|improve this answer
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.