在(ba)sh脚本中,如何忽略找不到文件的错误?
我正在编写一个从stdin读取(部分)文件名的脚本,使用:
read file; $FILEDIR/$file.sh
我需要给脚本的功能,以拒绝不存在的文件名。
例如:
$UTILDIR
不包含script.sh
用户类型脚本
脚本尝试访问$UTILDIR/script.sh
并失败,原因是
./run.sh: line 32: /utiltest/script.sh: No such file or directory
如何让脚本打印错误,但不打印“正常”错误而继续执行脚本?
发布于 2012-04-15 00:55:02
您可以使用@gogaman答案中的代码测试该文件是否存在,但您可能更感兴趣的是知道该文件是否存在和可执行。为此,您应该使用-x
测试而不是-e
if [ -x "$FILEDIR/$file.sh" ]; then
echo file exists
else
echo file does not exist or is not executable
fi
发布于 2012-04-15 00:48:04
if [ -e $FILEDIR/$file.sh ]; then
echo file exists;
else
echo file does not exist;
fi
发布于 2012-04-15 00:57:42
在这里,我们可以定义一个仅当文件存在时才运行的shell过程
run-if-present () {
echo $1 is really there
}
[ -e $thefile ] && run-if-present $thefile
https://stackoverflow.com/questions/10158596
复制