我已经尝试了所有可用的堆栈溢出解决方案,但是当我使用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
基于退出状态的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
我在你的代码中看到2个问题:
if [[ $isInFile == 0 ]];
—If条件不应以;
终止。删除。- 你正在检查的表达式总是一个空字符串。试试
echo $isInFile
。您要检查的是命令的输出,而不是它的返回值。相反,您应该从grep
表达式中删除-q
,并检查输出是否为空。
以下代码应该可以工作:
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
检查变量是否为空