Itération 122442
Itération 122442

Reputation: 2972

Bash equality not behaving as I expect it

I want to check if last command failed or not in bash. I base this mini script on this

#!/bin/bash
mkdir nothere/cantcreate

echo $?

if [ $? -eq 0 ]; then
    echo "command succeed"
    else
    echo "command failed"
fi

This prints the following:

mkdir: cannot create directory ‘nothere/cantcreate’: No such file or directory

1

command succeed

I expect it to print command failed as the value of $? is 1. Why does the equality not behave as I expect ?

Upvotes: 0

Views: 34

Answers (2)

Quasímodo
Quasímodo

Reputation: 4004

As mentioned in comment section, when you get to the if-clause $? evaluates to the exit code of echo $?.

The most straightforward and fool-proof way is to put the command itself in the if-clause:

#!/bin/bash
if mkdir nothere/cantcreate; then
    echo "command succeed"
else
    echo "command failed"
fi

Upvotes: 2

blami
blami

Reputation: 7411

echo $? itself is command that succeeds printing exit code of failed mkdir. If you want to capture exit code of mkdir you need to store it right after command call.

#!/bin/bash
mkdir nothere/cantcreate
RESULT=$?
echo $RESULT

if [ $RESULT -eq 0 ]; then
  echo "command succeed"
else
  echo "command failed"
fi

Upvotes: 1

Related Questions