是“$”吗?(美元问号)变量仅在 Bash shell 中可用?

Nan*_*iao 12 shell bash portability

Bashshell中,我可以通过$?变量获取命令退出状态:

# ps -ef | grep "haha"
root     15439 15345  0 23:02 pts/0    00:00:00 grep --color=auto haha
# echo $?
0
Run Code Online (Sandbox Code Playgroud)

它仅在 Bash shell 中可用吗?或者我也可以在其他 shell 中使用它?

Tho*_*key 20

$?退出代码是共同的后面POSIX任何壳,和在被描述2.5.2特殊参数

?
扩展到最近管道的十进制退出状态(请参阅管道)。

  • 不仅是 POSIX shell,所有类似 Bourne 的 shell,包括 Bourne shell(我相信它是引入它的那个,我相信 Mashey shell 把它称为 `$r`)。所以这是自 70 年代后期 Unix V7 以来几乎所有类 Unix 系统的 sh,大多数其他 shell(csh、tcsh、fish、rc)都将其作为 `$status`。 (5认同)
  • 以及许多脚本语言:Perl、Ruby 等。 (2认同)

apr*_*boy 13

正如 Thomas Dickey 所说,任何 POSIX shell(即几乎所有的 shell)都会有$?.

这个问题让我很感兴趣,所以我在我能接触到的任何 shell 上测试了它:

  • mksh
  • zsh
  • /bin/sh 在我的三星 Galaxy S5 上
  • /bin/sh 在我的路由器上
  • tcsh
  • ksh
  • dash
  • /bin/sh 在我 1989 年左右的虚拟 UNIX System V 上
  • cmd.exepowershell.exe我的Windows 10计算机上

$?在所有这些中工作,但是fishcmd.exe

发现两件有趣的事:

1.$?在Windows PowerShell中工作!

嗯,说到点子上了。而不是返回 0 或更高的数字,它只是Trueand 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
Run Code Online (Sandbox Code Playgroud)

2.$?在 shell 中不起作用fish

但是,当您输入$?fish 时,您会收到以下消息:

~$ echo $?
$? is not the exit status. In fish, please use $status.
fish: echo $?
Run Code Online (Sandbox Code Playgroud)

我没怎么用过但我并不感到惊讶,fish似乎有自己有趣的 shell 语言,完全不同bash或什么的。

  • 只取决于你如何阅读。我在心里读到`$?` 为“sh## 发生了?” 在那之后,我再也没有忘记这个特殊变量的含义:) (3认同)
  • @nwildner 哈哈!我想我现在永远不会忘记! (2认同)