Skip to main content

How to Check Whether the Last Command Worked with $? in bash and zsh

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Every command ends with an exit status: 0 when it worked and another number when it failed. The shell keeps the last one in $?, so echo $? tells you whether the command before it worked. This guide runs mkdir twice, with real output from zsh 5.9 and bash 3.2.

Syntax​

Syntax
<command>
echo $?
PartWhat it means
<command>The command whose result you want to check
$?The exit status of the most recent command. 0 means it worked

The bash manual: "Expands to the exit status of the most recently executed command." On what the numbers mean, its Exit Status page: "while an exit status of zero indicates success, a non-zero exit status indicates failure."

Prerequisites​

  • zsh or bash. This guide uses zsh 5.9, the default shell on macOS, and checks every command in bash 3.2 too.

Step 1: Run mkdir Twice​

mkdir reports creates a folder named reports. The second time, the folder already exists:

Terminal
mkdir reports
echo $?
mkdir reports
echo $?
Output
0
mkdir: reports: File exists
1

zsh running mkdir reports and echo $?, which prints 0, then mkdir reports again, which fails with File exists, and echo $?, which prints 1.

The first mkdir created the folder, and its exit status was 0. The second failed, and its status was 1. bash printed the same.

Common Mistakes​

MistakeWhat happensDo this instead
Running another command before reading $?$? then holds that command's status: after a failed mkdir and echo "Done", it printed 0Read $? right after the command you're checking

Troubleshooting​

SymptomLikely causeFix
$? is 0 although a command failedAnother command ran in betweenCheck $? straight after the command

FAQ​

Is every failure a 1?​

No. 0 always means success, but failures can use other numbers: grep ERROR nothing.log, on a file that doesn't exist, failed with 2. The bash manual says the scheme gives "one well-defined way to indicate success and a variety of ways to indicate various failure modes." A command's manual page lists the numbers it uses.

Does $? work the same in zsh and bash?​

Yes. The zsh manual describes it as "The exit status returned by the last command.", and bash printed the same 0 and 1 for the two mkdir commands.

Conclusion​

echo $? printed 0 after the mkdir that worked and 1 after the one that failed. Read $? straight after a command to know whether it worked.

Additional Resources​