Intermediate Bash - test and if

Question Click to View Answer

What is the exit status of the following command: $ ls /fake_dir/

# run the command
ls /fake_dir/

# get the exit status
echo $?

The exit status of the most recently executed command is stored in the ? variable. By convention, an exit status of 0 represents success and any other exit status represents failure. In this example, the exit status is 1 to represent that the ls command failed to run properly.

What is the exit status of the following command: $ ls $HOME

# run the command
ls $HOME

# get the exit status
echo $?

The exit status is 0 because the ls command ran successfully.

What is the exit status of the true command.

# run the command
true

# get the exit status
echo $?

The true command always returns an exit code of zero.

What is the exit status of the false command.

# run command
false

# get the exit status
echo $?

The exit status is 1 and the false utility always exits with a nonzero exit code.

Return an exit code of 0 if the number 5 is greater than the number 3 and a nonzero exit code otherwise.

# run command
test 5 -gt 3

# get the exit status
echo $?

The test command evaluates the expression and returns 0 if it's true and 1 if it's false. 5 is greater than 3, so the test command returns an exit code of 0.

What does the following code print:

[ 40 -eq 30 ]
echo $?

1

The test command can also be executed with the following syntax: [ expression ]. These lines are equivalent:

test 40 -eq 30
[ 40 -eq 30 ]

40 is not equal to 30, so the test command exits with a code of 1.

What does the following code print?

if true; then
  echo "woo hoo"
fi
"woo hoo"

The condition in this example exits with a status of 0, so the code in the if block is executed.

What does the following code print?

if [ 40 -eq 90 ]; then
  echo 'moooo'
fi

This code doesn't print anything. The condition in this example ([ 40 -eq 90]) exits with a status of 1, so the code in the block is not executed.

What does the following code print?

if test 55 -lt 44; then
  echo 'i love numbers'
else
  echo 'nooooooo'
fi
'nooooooo'

test 55 -lt 44 exits with a status code of 1, so the code in the if block is not executed and the code in the else block is executed. The condition could have also been written with the more common bracket syntax: [ 55 -lt 44 ]