【问题标题】:How to get bash to ignore file-not-founds如何让 bash 忽略文件未找到
【发布时间】:2012-04-15 00:33:54
【问题描述】:

在 (ba)sh 脚本中,如何忽略 file-not-found 错误?

我正在编写一个从标准输入读取(部分)文件名的脚本,使用:

read file; $FILEDIR/$file.sh

我需要提供脚本功能来拒绝不存在的文件名。

例如

$UTILDIR 不包含script.sh 用户类型脚本
脚本尝试访问 $UTILDIR/script.sh 并失败为

./run.sh: line 32: /utiltest/script.sh: No such file or directory

如何让脚本打印错误,但继续执行脚本而不打印“正常”错误?

【问题讨论】:

    标签: bash file-not-found


    【解决方案1】:

    您可以使用@gogaman 答案中的代码测试文件是否存在,但您可能更感兴趣的是知道该文件是否存在并且可执行。为此,您应该使用-x 测试而不是-e

    if [ -x "$FILEDIR/$file.sh" ]; then
       echo file exists
    else
       echo file does not exist or is not executable
    fi
    

    【讨论】:

      【解决方案2】:
      if [ -e $FILEDIR/$file.sh ]; then
       echo file exists;
      else
       echo file does not exist;
      fi
      

      【讨论】:

        【解决方案3】:

        这里我们可以定义一个只有在文件存在时才运行的shell过程

        run-if-present () {
          echo $1 is really there
        }
        
        [ -e $thefile ] && run-if-present $thefile
        

        【讨论】:

        • 这引入了竞争条件。
        • @tikiking1:该文件可能在测试和命令之间被删除,因此run-if-present 中该文件可能实际上不存在。 run-if-present 还是要处理这个案子。
        【解决方案4】:

        根据您对脚本执行的操作,该命令将失败并显示特定的退出代码。如果您正在执行脚本,则退出代码可以是 126(权限被拒绝)或 127(未找到文件)。

        command
        if (($? == 126 || $? == 127))
        then
          echo 'Command not found or not executable' > /dev/stderr
        fi
        

        【讨论】:

        • 这是我附加的(修改后的版本),它接收实用程序的返回。虽然不完全是我正在寻找的东西,但这很有帮助。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-12
        • 2016-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-28
        相关资源
        最近更新 更多