2009-11-17 57 views
0

所以,假設我有一個命令,foo,在一個既有返回值又有我感興趣的輸出字符串的腳本中,並且我想將它們存儲到一個變量中(至少它的輸出爲變量,其返回值可用於條件)。有沒有辦法捕獲命令的輸出,並將其返回值轉換爲shell腳本中的變量?

例如:

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 

反正是有,我可以簡化?

回答

4

這個?

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`) 
+0

是啊,你說得對反引號的事情。我不知道爲什麼我把那些放在那裏。 – supercheetah 2009-11-17 03:17:51

+0

感謝的方式 – supercheetah 2009-11-17 03:18:28

3
output=`foo` 
echo "Return: $?" # $? is the return code 
相關問題