Is the "$?" (dollar-question mark) variable available only in the Bash shell?

In the Bash shell, I can get the command exit status through the $? variable:

# ps -ef | grep "haha"
root     15439 15345  0 23:02 pts/0    00:00:00 grep --color=auto haha
# echo $?
0

Is it available only in the Bash shell? Or can I also use it in other shells?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The $? exit-code is common to any shell that follows POSIX, and is described in 2.5.2 Special Parameters:

?
Expands to the decimal exit status of the most recent pipeline (see Pipelines).

Solution 2

As Thomas Dickey said, any POSIX shell (ie. pretty much all of them) will have $?.

This question interested me quite a bit, so I tested it on any shell I could get my hands on:

  • mksh
  • zsh
  • /bin/sh on my Samsung Galaxy S5
  • /bin/sh on my router
  • tcsh
  • ksh
  • dash
  • /bin/sh on my virtual UNIX System V from 1989 or so
  • cmd.exe and powershell.exe on my Windows 10 computer

and $? worked in all of these but fish and cmd.exe.

Found two interesting things:

1. $? works in Windows PowerShell!

Well, to a point. Instead of returning 0 or a higher number, it’s just True and False.

PS C:\WINDOWS\system32> echo $?
True
PS C:\WINDOWS\system32> gfdhgfhfdgfdg
gfdhgfhfdgfdg : The term 'gfdhgfhfdgfdg' is not recognized as the name of a cmdlet, ...(big long error output).....
PS C:\WINDOWS\system32> echo $?
False

2. $? doesn’t work in the shell fish.

However, when you type $? in fish, you get this message:

~$ echo $?
$? is not the exit status. In fish, please use $status.
fish: echo $?

I haven’t used it much but I’m not surprised, fish seems to have its own interesting shell language, completely different from bash or whatever.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply