Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit code of redirected command

So I want to verify the exit code of a specific command

runuser -s /bin/bash @user_name -c $command > /dev/null 2>&1 &

How can I find whether the command runuser -s /bin/bash @user_name -c $command executed correctly? I tried using $? but it doesn't work because it is always 0 ( the result of redirection is 0)

How can i find the exit code of that command ?

like image 322
user2576439 Avatar asked Jul 12 '13 12:07

user2576439


People also ask

How do I find command exit code?

Extracting the elusive exit code To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.

What is exit code 1 in shell script?

Exit Code 1 indicates that a container shut down, either because of an application failure or because the image pointed to an invalid file. In a Unix/Linux operating system, when an application terminates with Exit Code 1, the operating system ends the process using Signal 7, known as SIGHUP.

What is exit code of command false '?

false returns an exit status value of 1 (failure). It ignores any arguments given on the command line. This option can be useful in shell scripts.


2 Answers

The exit code is not available due to the backgrounding of the task (via &), not the redirection.

You should use wait to get the exit code of a background task.

wait command stop script execution until all jobs running in background have terminated, or until the job number or process id specified as an option terminates. It returns the exit status of waited-for command.

like image 144
Brian Agnew Avatar answered Sep 28 '22 16:09

Brian Agnew


You can use $! in bash to get the pid of last background process. Then you can do wait pid. This waits until the process with pid is complete.

So for your script you can do something like this:

runuser -s /bin/bash @user_name -c $command > /dev/null 2>&1 &
myPid=$!
wait $myPid
status=$?
echo "Exit status of the process with pid: $myPid is $status"
like image 39
anubhava Avatar answered Sep 28 '22 16:09

anubhava