huahsin68
huahsin68

Reputation: 6989

How to check command status while redirect standard error output to a file?

I have a bash script having the following command

rm ${thefile}

In order to ensure the command is execute successfully, I use $? variable to check on the status, but this variable doesn't show the exact error? To do this, I redirect the standard error output to a log file using following command:

rm ${file} >> ${LOG_FILE} 2>&1

With this command I can't use $? variable to check status on the rm command because the command behind the rm command is executed successfully, thus $? variable is kind of useless here.

May I know is there a solution that could combine both features where I'm able to check on the status of rm command and at mean time I'm allow to redirect the output?

Upvotes: 1

Views: 1623

Answers (2)

konsolebox
konsolebox

Reputation: 75608

What you probably need is the shell option pipefail in bash (from man bash):

The return status of a pipeline is the exit status of the last command, unless the pipefail option is enabled. If pipefail is enabled, the pipeline's return status is the value of the last (rightmost) command to exit with a non-zero sta‐ tus, or zero if all commands exit successfully. If the reserved word ! precedes a pipeline, the exit status of that pipeline is the logical negation of the exit status as described above. The shell waits for all commands in the pipeline to terminate before returning a value.

> shopt -s -o pipefail
> true | false
> echo $?
1
> false | true
> echo $?
1
true | true
echo $?
0

Upvotes: 1

ruakh
ruakh

Reputation: 183602

With this command I can't use $? variable to check status on the rm command because the command behind the rm command is executed successfully, thus $? variable is kind of useless here.

That is simply not true. All of the redirections are part of a single command, and $? contains its exit status.

What you may be thinking of is cases where you have multiple commands arranged in a pipeline:

command-1 | command-2

When you do that, $? is set to the exit status of the last command in the pipeline (in this case command-2), and you need to use the PIPESTATUS array to get the exit status of other commands. (In this example ${PIPESTATUS[0]} is the exit status of command-1 and ${PIPESTATUS[1]} is equivalent to $?.)

Upvotes: 6

Related Questions