2016-04-26 113 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