Search code examples
bashexit-code

Bash Exit Code Status script error


#!/bin/bash
# exitlab
#
# example of exit status
# check for non-existent file 
# exit status will be 2
# create file and check it
# exit status will be 0
#
ls xyzzy.345 > /dev/null 2>&1
status='echo $?'
echo "status is $status"

# create the file and check again
# status will not be 0
touch xyzzy.345

ls xyzzy.345 > /dev/null 2>&1
status='echo $?'
echo "status is $status"

#remove the file
rm xyzzy.345

edx.org has a Lab and this is the script. When I run it, the output is as follows:

status is echo $?
status is echo $?

I think the output is supposed to be either 0 or 2. I tried putting parentheses like status='(echo $?) but that results in status is echo $?. Then, I tried putting parentheses outside of the single quotes status=( 'echo $?' ) but this gave me the same output status is echo $?.

Any ideas?


Solution

  • You need to use double-quotes here for the variable substitution to take place. Change

    status='echo $?'
    

    to

    status="echo $?"
    

    You might find this guide helpful: Bash Guide for Beginners