我已經嘗試了堆疊溢位時可用的所有解決方案,但是當我使用 if 條件時,它總是結果為真。我需要在檔案中找到一行并查看它是否不退出然后將該行插入該檔案中,但它總是導致該行已經存在。這是我的腳本
isInFile=$(grep -q '^export' /etc/bashrc)
if [[ $isInFile == 0 ]];
then
echo "line is not present";
echo "export PROMPT_COMMAND='RETRN_VAL=\$?;logger -p local6.debug \"\$(whoami) [\$\$]: \$(history 1 | sed \"s/^[ ]*[0-9]\ [ ]*//\" )\"'" >> /etc/bashrc;
source /etc/bashrc;
else
echo "line is in the file";
fi
它總是說
line is in the file
uj5u.com熱心網友回復:
該if陳述句根據給出的命令的退出狀態進行分支。[[只是您可以使用的一個命令,它不是強制性語法。在互動式提示下,輸入help if
做這個:
if grep -q '^export' /etc/bashrc
then
# exit status of grep is zero: the pattern DOES MATCH the file
echo "line is in the file";
else
# exit status of grep is non-zero: the pattern DOES NOT MATCH the file
echo "line is not present";
echo "export PROMPT_COMMAND='RETRN_VAL=\$?;logger -p local6.debug \"\$(whoami) [\$\$]: \$(history 1 | sed \"s/^[ ]*[0-9]\ [ ]*//\" )\"'" >> /etc/bashrc;
source /etc/bashrc;
fi
uj5u.com熱心網友回復:
我在您的代碼中看到 2 個問題:
if [[ $isInFile == 0 ]];--如果條件不應該以;. 洗掉它。- 您正在檢查的運算式始終是一個空字串。試試
echo $isInFile。您正在檢查的是命令的輸出,而不是它的回傳值。相反,您應該-q從grep運算式中洗掉并檢查輸出是否為空。
以下代碼應該可以作業:
isInFile=$(grep '^export' /etc/bashrc)
if [ -z "$isInFile" ]
then
echo "line is not present";
echo "export PROMPT_COMMAND='RETRN_VAL=\$?;logger -p local6.debug \"\$(whoami) [\$\$]: \$(history 1 | sed \"s/^[ ]*[0-9]\ [ ]*//\" )\"'" >> /etc/bashrc;
source /etc/bashrc;
else
echo "line is in the file";
fi
-z檢查變數是否為空。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/466166.html
