Breako Breako
Breako Breako

Reputation: 6461

Get numeric return value from command

In a bash shell if a command is successful it returns 0, and if unsuccessful it returns a another number. How do I get the number returned?

For example, I want the return code number returned from the ls command

I try:

echo $ls
echo $(ls)
echo $(?ls)

But none give me what I am looking for. Any tips?

Upvotes: 1

Views: 359

Answers (2)

Arkku
Arkku

Reputation: 42139

The special variable $? contains the previous command's return status.

For example:

ls
echo $?
false
echo $?

Note that if you run another command before checking $?, its value will be that of the new command:

false
echo $? # prints the return status of false
echo $? # now prints the return status of the previous echo

So if you wish to use the status more than once, save it to a variable (e.g., err=$?).

Upvotes: 2

Chris Hayes
Chris Hayes

Reputation: 12040

After running a command, the $? variable will contain the command's exit code.

# This prints 0..
ls; echo $?

# .. and this prints 1
(exit 1); echo $?

Upvotes: 5

Related Questions