Kent Pawar
Kent Pawar

Reputation: 2606

What causes the exit status to change for the same command even when the output is identical?

In the below code, I am trying to check if the command within the if condition completed successfully and that the data was pushed into the target file temp.txt.

Consider:

#!/usr/bin/ksh

A=4
B=1

$(tail -n $(( $A - $B )) sample.txt > temp.txt)
echo "1. Exit status:"$?

if [[ $( tail -n $(( $A - $B )) sample.txt > temp.txt ) ]]; then
    echo "2. Exit status:"$?
    echo "Command completed successfully"
else
    echo "3. Exit status:"$?
    echo "Command was unsuccessfully"
fi  

Output:

$ sh sample.sh
1. Exit status:0
3. Exit status:1

Now I can't get why the exit status changes above.. when the output of both the instances of the tail commands are identical. Where am I going wrong here..?

Upvotes: 0

Views: 175

Answers (1)

Miklos Aubert
Miklos Aubert

Reputation: 4585

In the first case, you're getting the exit status of a call to the tail command (the subshell you spawned with $() preserves the last exit status)

In the second case, you're getting the exit status of a call to the [[ ]] Bash built-in. But this is actually testing the output of your tail command, which is a completely different operation. And since that output is empty, the test fails.

Consider :

$ [[ "" ]]           # Testing an empty string
$ echo $?            # exit status 1, because empty strings are considered equivalent to FALSE
1
$ echo               # Empty output

$ echo $?            # exit status 0, the echo command executed without errors
0
$ [[ $(echo) ]]      # Testing the output of the echo command
$ echo $?            # exit status 1, just like the first example.
1
$ echo foo
foo
$ echo $?            # No errors here either
0
$ [[ $(echo foo) ]]
$ echo $?            # Exit status 0, but this is **NOT** the exit status of the echo command.
0

Upvotes: 1

Related Questions