shell脚本以检查文件中是否存在一行
我尝试了堆栈溢出上可用的所有解决方案,但是当我使用条件时,始终会导致结果为true。 我需要在文件中找到一条线,看看它是否没有退出,然后在该文件中插入该行,但始终会导致该行已经存在。 这是我的脚本,
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
I have tried all the solutions available on stack overflow, but when I use if condition with with it always results true.
I need to find a line in the file and see if it doesn't exit then insert the line in that file, but it always results that the line already exists.
Here is my script
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
It always says that
line is in the file
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果
语句分支基于的退出状态它给定的。[[
只是您可以使用的一个命令,而不是强制性语法。在交互提示下,如果执行此操作,请输入
帮助:
The
if
statement branches based on the exit status of the command it's given.[[
is just one command you can use, it's not mandatory syntax. At an interactive prompt, enterhelp if
Do this:
我在您的代码中看到2个问题:
如果[[$ isInfile == 0]];
- 如果条件不应使用;
终止。删除。echo $ isInfile
。您要检查的是命令的输出,而不是其返回值。相反,您应该从grep
表达式中删除-Q
,并检查输出是否为空。以下代码应起作用:
-z
检查可变的空虚。I see 2 issues in your code:
if [[ $isInFile == 0 ]];
--If condition should not terminate with;
. Remove that.echo $isInFile
. What you are checking is output of the command, not its return value. Instead, you should remove-q
from yourgrep
expression and check if the output is empty or not.Following code should work:
-z
check for emptiness of variable.