linux - 如果在反引号中为变量分配命令表达式会发生什么

标签 linux bash

下面是bash的代码:

a=`echo hello`
echo $a

输出是:

hello

但我认为应该是:

hello
0

最佳答案

你想错了;-)

将命令放在反引号中会将右侧表达式的输出 (stdout) 分配给左侧的变量。

$? 为您提供命令的“输出状态”(或返回代码)——也就是您期望的“0”。

所以:

a=`echo hello`

运行命令“echo hello”,但不是回显到标准输出,而是“回显”到可变的a。所以 a=whatever_the_command_would_have_written_to_stdout(在本例中为“hello”)——实际上没有任何内容写入 stdout,因为它被 ``s“捕获”

关于linux - 如果在反引号中为变量分配命令表达式会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38603198/

相关文章:

python - 我的 Python 代码有多少个线程?

Linux 自动启动

bash - bash(配置文件)中类似数组的数据结构?

linux - Ash MATCH 运算符 (=~)

linux - 使用 sudo 命令时是否应该首先获取文件?

java - 如何解决 "no db_java-6.2 in java.library.path"问题?

Linux权限文件

java - Tomcat启动和停止使用shell脚本?

python - 将 bash/python 脚本与 Selenium 集成

linux - bash 在 screen 内时,如果不适合一行,输出将被截断