在(ba)sh脚本中,如何忽略文件未找到的错误?
我正在编写一个脚本,它从stdin中读取(部分)文件名,使用:
read file; $FILEDIR/$file.sh
我需要提供脚本功能来拒绝不存在的文件名。
e.g。
$UTILDIR
不包含script.sh
用户类型脚本
脚本尝试访问$UTILDIR/script.sh
并失败为
./run.sh: line 32: /utiltest/script.sh: No such file or directory
如何让脚本打印错误,但是在不打印“正常”错误的情况下继续脚本?
答案 0 :(得分:1)
if [ -e $FILEDIR/$file.sh ]; then
echo file exists;
else
echo file does not exist;
fi
答案 1 :(得分: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 :(得分:1)
这里我们可以定义一个仅在文件存在的情况下运行的shell过程
run-if-present () {
echo $1 is really there
}
[ -e $thefile ] && run-if-present $thefile
答案 3 :(得分:0)
根据您对脚本执行的操作,该命令将失败并显示特定的退出代码。如果您正在执行脚本,则退出代码可以是126(权限被拒绝)或127(未找到文件)。
command
if (($? == 126 || $? == 127))
then
echo 'Command not found or not executable' > /dev/stderr
fi