1

I noticed something strange (at least for me it's strange). I am writing a script and I need 0 or 1 as exit codes. So far so good. I have them in a simple if-else with echo $? above each condition but when I make the echo $? as a variable to call it's always showing 0 as exit code.

#!/bin/bash

exit=`echo $?`

DIRECTORY="/some/dir"

if [[ $(stat -c "%a" "$DIRECTORY") == "777" ]]
then
        echo $?
        #echo "The exit code is: $exit"
else
        echo $?
        #echo "The exit code is: $exit"
fi

#EOF

If use just "echo $?" it's all good. I receive 0 or 1. But in the commented part I always receive 0.

4
  • 1
    When is exit=`echo $?` evaluated?
    – Josh Lee
    Commented May 14, 2018 at 13:46
  • I am not sure I am understanding the question? How come evaluated and which one - the one above the conditional or these inside?
    – slaffcheff
    Commented May 14, 2018 at 13:49
  • exit=$? works just as well as exit=$(echo $?).
    – chepner
    Commented May 14, 2018 at 14:06
  • 2
    It occurs to me that this is rather unclear. Do you want the status of the stat command or of the test? Commented May 14, 2018 at 14:08

2 Answers 2

4

The $? construct contains the status code of the last command executed - exactly the last command.

The [[ is a command (bash test). Hence, you are testing the result of test.

To fix it, save the result first. For example:

result=$(stat -c "%a" "$DIRECTORY")
status=$?
... do stuff with status and result
1
  • I assumed that was what the OP wanted.
    – rghome
    Commented May 14, 2018 at 14:34
3

You set the value of exit at the top of the code. This remains unchanged throughout the script. This is why you always get the same value.

Instead:

#!/bin/bash

dir='/some/dir'

if [[ "$(stat -c "%a" "$dir")" == "777" ]]; then
    status=0
    printf 'Permissions are 777 (status=%d)\n' "$status"
else
    status=1
    printf 'Permissions are not 777 (status=%d)\n' "$status"
fi

or

#!/bin/sh

dir='/some/dir'

case "$(stat -c "%a" "$dir")" in
    777) echo 'Permissions are 777';     status=0 ;;
    *)   echo 'Permissions are not 777'; status=1 ;;
esac

Note that there is actually no need to investigate $? here. If the test succeeds, you know that it's going to be 0, otherwise non-zero.

Not the answer you're looking for? Browse other questions tagged or ask your own question.