![](/img/trans.png)
[英]How to store the output of command “which” in a variable in a bash script?
[英]How to store output from a bash command in a variable
您好,我正在嘗試將OS X命令存儲在變量中,但是這樣做有問題。 這是我的代碼:
#! /bin/bash
Output=$(dscl . -read /Users/root AuthenticationAuthority)
Check="No such key: AuthenticationAuthority"
if [ "$Output" = "$Check" ]
then
echo "OK"
else
echo "FALSE"
fi
我之前已經使用“ defaults read ....”之類的命令完成了此操作,但dscl可以正常工作。 -read不會將輸出存儲在變量中。 有任何想法嗎?
失敗時,dscl命令以及所有標准的shell命令都會在stderr上輸出錯誤消息,而$(...)
僅捕獲stdout。
您必須首先合並兩個流:
Output=$(dscl . -read /Users/root AuthenticationAuthority 2>&1)
當dscl
命令成功執行時,其輸出將到達stdout
,該值由命令替換捕獲。
出現錯誤時,消息將打印到stderr
。
為了捕捉無論是stdout
或stderr
,你可以重定向stderr
的命令去stdout
:
Output=$(dscl . -read /Users/root AuthenticationAuthority 2>&1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.