1

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?

2 Answers 2

5

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 $?
Sign up to request clarification or add additional context in comments.

2 Comments

The variable is called ?, placing the $ operator on the LHS gives the value.
Fair point, thanks. Worth noting is that it's not assignable like other variables (at least not through any basic testing I tried).
2

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=$?).

2 Comments

The special variable is called ?, placing the $ operator on the LHS gives the value.
@cdarke True, but in the context I think it's clearer to say $?.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.