2016-04-26 80 views
1
#!/bin/bash 
# exitlab 
# 
# example of exit status 
# check for non-existent file 
# exit status will be 2 
# create file and check it 
# exit status will be 0 
# 
ls xyzzy.345 > /dev/null 2>&1 
status='echo $?' 
echo "status is $status" 

# create the file and check again 
# status will not be 0 
touch xyzzy.345 

ls xyzzy.345 > /dev/null 2>&1 
status='echo $?' 
echo "status is $status" 

#remove the file 
rm xyzzy.345 

edx.org有一個實驗室,這是腳本。當我運行它時,輸出如下:Bash退出代碼狀態腳本錯誤

status is echo $? 
status is echo $? 

我想輸出應該是0或2。我試圖把括號一樣status='(echo $?)但導致status is echo $?。然後,我嘗試在單引號status=('echo $?')之外放置括號,但是這給了我相同的輸出status is echo $?

任何想法?

+0

我會用'回聲 「狀態爲」 $'或'STT = $ ?;回聲「狀態是」$ stt' –

回答

-1

您需要在這裏使用雙引號進行變量替換。更改

status='echo $?' 

status="echo $?" 

您可能會發現該指南有價值:Bash Guide for Beginners

+0

謝謝。這產生了正確的輸出'狀態是回聲2'並且 '狀態是回聲0'。請回答我的問題,以便我可以給你點。 – Debug255

+0

我猜你對引用的工作方式感興趣,而不是反引號。我已經更新了我的答案。單引號保護$,而雙引號允許替換髮生。 HTH – Dinesh

1

您正在尋找命令替換(status=$(echo $?)),儘管它是沒有必要的。您可以直接分配的$?價值status

status=$? 
+0

謝謝。這是edx.org提供的課程。您的建議對我可能需要使用的腳本有意義。 – Debug255