10

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?

19

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).

  • 5
    Not only POSIX shell, all Bourne-like shells including the Bourne shell (which I believe was the one introducing it, the Mashey shell had it as $r I believe). So that's the sh of virtually all Unix-like systems since Unix V7 in the late 70s, Most other shells (csh, tcsh, fish, rc) have it as $status. – Stéphane Chazelas Jan 18 '16 at 11:33
  • 2
    And many scripting languages: Perl, Ruby, etc. – OrangeDog Jan 18 '16 at 13:52
13

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.

  • Most shells (fish, csh, tcsh, rc, zsh) use $status which is a lot more straightforward/legible IMO. Only Bourne-like shells (among Unix shells) use $? AFAIK. – Stéphane Chazelas Jan 18 '16 at 11:35
  • 3
    Just depends on how you are reading. I read mentally $? as "sh## happened?" and after that, i never forgot the meaning of this special variable :) – user34720 Jan 18 '16 at 12:58
  • 2
    @nwildner lol! I think I'll never forget that now! – hanetzer Jan 18 '16 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.