有没有办法捕获命令的输出及其返回值到 shell 脚本中的变量中?
因此,假设我在一个脚本中有一个命令 foo
,它既有返回值,又有我感兴趣的输出字符串,并且我想将它们存储到变量中(至少它的变量输出,并且它的返回值可以用于条件)。
例如:
a=$(`foo`) # this stores the output of "foo"
if foo; then # this uses the return value
stuff...
fi
我能想到的捕获该输出的最好方法是使用一些临时文件:
if foo > $tmpfile; then
a=$(`cat $tmpfile`)
stuff...
fi
无论如何我可以简化它吗?
So, let's say that I have a command, foo
, in a script which has both a return value, and an output string that I'm interested in, and I want to store those into a variable (well at least its output for the variable, and its return value could be used for a conditional).
For example:
a=$(`foo`) # this stores the output of "foo"
if foo; then # this uses the return value
stuff...
fi
The best thing that I could think of to capture that output is to use some temporary file:
if foo > $tmpfile; then
a=$(`cat $tmpfile`)
stuff...
fi
Is there anyway I could simplify that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这?
顺便说一句,$() 和反引号是具有相同效果的两种语法,这意味着您仅想要编写
if
foo
输出您想要再次执行的命令的文本。喜欢:this?
btw, $() and backticks are two syntaxes for the same effect, which means that you only want to write
if
foo
outputs a text of a command you want to execute again. like:来自 bash:(注意第一列中的第一个 $ 是我的提示符)
不要使用
$()
加反引号,因为它实际上执行命令,然后执行其输出。另请参阅:
From bash: (note the first $ in the first column is my prompt)
Don't use
$()
plus backticks, as that actually executes the command and then executes its output.See also: