![](/img/trans.png)
[英]How to capture the output of telnet command in a variable in Shell script
[英]Is there a way to capture the output of a command, and its return value into variables in a shell script?
因此,假設我在腳本中有一個命令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
無論如何,我可以簡化一下嗎?
這個?
out=$(cmd)
rv=$?
if test $rv -eq 0; then
echo "all good"
echo $out
else
echo "wtf, exit code was $rv"
fi
順便說一句,$()和反引號兩種語法達到相同的效果,這意味着你只需要編寫
$(`foo`)
如果foo
輸出您要再次執行的命令的文本。 喜歡:
foo()
{
echo echo date
}
$(foo)
$(`foo`)
output=`foo`
echo "Return: $?" # $? is the return code
從bash:(請注意第一欄中的第一個$是我的提示)
$ A=$(echo abc; false); echo status:$? A:$A
status:1 A:abc
不要使用$()
加上反引號,因為這實際上會執行命令,然后執行其輸出。
也可以看看:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.