【问题标题】:Need some help writing an if statement in UNIX bash scripting在 UNIX bash 脚本中编写 if 语句需要一些帮助
【发布时间】:2013-06-16 12:58:24
【问题描述】:

我正在编写一个相当长的脚本(或者我认为很长的脚本 - 您可能会在几个小时内完成)。我基本上有一个文件(名为 .restore.info),其中包含名称文件。在脚本的一部分,我想测试“如果在 .restore.info 中找不到文件名,然后说“错误:恢复的文件不存在”。如果这对你们没有意义,请道歉(对我来说,确实如此在宏伟的计划中)。所以如果在命令行中输入:

sh MYSCRIPT filename

它将在 .restore.info 文件中搜索字符串文件名,如果找不到任何内容,它应该会产生错误消息。

基本上,我需要将这段代码的第一行翻译成一个 UNIX bash 语句和一些真正有意义的东西!:

If grep $1 .restore.info returns an exist status of 1; then
  echo “Filename does not exist!”
fi

提前致谢!请问我是否需要我更清楚地澄清任何事情,因为我知道我不是最好的解释者,我会在一分钟内回复您! (当然会给出+rep和最佳答案!)

【问题讨论】:

    标签: bash unix if-statement grep sh


    【解决方案1】:

    使用grep -q

    grep -q "filename" .restore.info && echo "found match"
    

    ! grep -q "filename" .restore.info && echo "not found"
    

    【讨论】:

    • 你不想把grep放在$()里面
    【解决方案2】:

    您可能只关心grep 是否以非零退出状态退出:

    if ! grep -q "$1" .restore.info; then
        echo "Filename does not exist!"
    fi
    

    但如果您确实关心特定的退出状态(在本例中为 1):

    if ! grep -q "$1" .restore.info && [[ $? -eq 1 ]]; then
        echo "Filename does not exist!"
    fi
    

    【讨论】:

      【解决方案3】:
      grep -l 'filename' .restore.info
      if [ $? = 0 ];then
         echo "found it"
      else 
        echo "not found"
      fi
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-09
        • 1970-01-01
        相关资源
        最近更新 更多