【问题标题】:Bash checking if file exists and then check for a substring in the file [duplicate]Bash检查文件是否存在,然后检查文件中的子字符串[重复]
【发布时间】:2019-02-10 22:37:07
【问题描述】:

我想检查文件是否存在,然后检查文件中的子字符串

if [ -f /etc/abc.conf ]; then
   if [ grep 'abc.conf' -e 'host.com' ]
    test = 'PASS'
   else 
    test = 'FAIL'
   fi
else
   echo "File doesnot exist"
fi

echo $test

如果有更好的方法,请告诉我

【问题讨论】:

  • 你问是因为这个 sn-p 不起作用吗?尝试shellcheck 找出错误和缺失的语法。
  • 有一个更好的方法,因为你现在拥有的东西根本就坏了。
  • @BenjaminW。怎么是复制品?答案中没有一个关于不存在文件的词:-(

标签: linux bash sed grep rhel


【解决方案1】:

是的,您的 grep 可能支持 -s 参数:

   -s, --no-messages
          Suppress error messages about nonexistent or unreadable files.

所以这样的事情应该可以工作:

grep -qs 'abc.conf' '/etc/abc.conf' && test='PASS' || test='FAIL'

【讨论】:

    【解决方案2】:

    如果文件不存在或不可读,Grep 返回 2,如果找不到字符串,则返回 1。

    grep -qs '<string>' file.txt
    res=$?
    if [ $res -eq 0 ]; then
      test='PASS'
    elif [ $res -eq 1 ]; then
      test='FAIL'
    elif [ $res -eq 2 ]; then
      echo "Cannot read file"
    else
      echo "Unrecognized return code ($res) from grep"
    fi
    

    【讨论】:

    • case $? in 0) test='PASS' ;; 等(顺便说一下,= 周围有多余的空格)
    • 这就是我复制粘贴的结果! :D 我会解决的。谢谢。
    • case 很好,但我不想添加他可能不知道的语法。
    猜你喜欢
    • 1970-01-01
    • 2012-05-26
    • 2013-05-19
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多