[英]Bash - Getting output of a command
No matter what I seem to do, I can't seem to get the output of a command to be assigned to a variable in bash. 无论我做什么,我似乎无法将命令的输出分配给bash中的变量。 Although my script runs find without any errors, I'm not getting the result I want: 虽然我的脚本运行发现没有任何错误,但我没有得到我想要的结果:
# Prompt if the user needs Qt
echo ""
echo "Checking for qt5-default."
echo ""
OUTPUT="$(sudo dpkg -s qt5-default)"
echo "OUTPUT:"
echo $OUTPUT
...
OUTPUT
will never echo anything. OUTPUT
永远不会回应任何东西。 However, if I do: 但是,如果我这样做:
OUTPUT="$(ls -la)"
Then it works. 然后它工作。 I'm wondering why. 我想知道为什么。
Here is what I mean: 这就是我的意思:
As you can see, the "OUTPUT:" string comes after the command output, which means that the output wasn't stored in the variable, but was run in the main shell, which confuses me. 正如您所看到的,“OUTPUT:”字符串位于命令输出之后,这意味着输出未存储在变量中,而是在主shell中运行,这让我感到困惑。
Here is what happens when OUTPUT="$(ls -la)"
: 当OUTPUT="$(ls -la)"
时会发生以下情况:
In this case, "OUTPUT:" comes before, showing that the echo
command worked correctly. 在这种情况下,“OUTPUT:”出现在之前,表明echo
命令正常工作。
Any ideas? 有任何想法吗?
OUTPUT=$( dpkg -s qt5-default 2>&1 )
Should do what you're after. 应该做你想要的。 As Etan pointed out, dpkg's output goes to stderr, not stdout. 正如Etan指出的那样,dpkg的输出转到stderr,而不是stdout。
dpkg -s
do not require root privileges. dpkg -s
不需要root权限。 As good practice never use sudo
inside of scripts, but require a root privileges for a script. 好的做法从不在脚本中使用sudo
,但需要脚本的root权限。
About your question: why it happens? 关于你的问题:为什么会这样? Because sudo
runs in sub-shell (brackets $(...)
opens a subshell) 因为sudo
在子shell中运行(括号$(...)
打开子shell)
I will try to find a good reference about bash pitfalls and subshell, I don't remember where I read about it. 我将尝试找到关于bash陷阱和子shell的一个很好的参考,我不记得我在哪里读到它。 Try this: Subshell Pitfalls 试试这个: Subshell陷阱
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.