我有一个将写入输出文件的 bash 程序。该文件可能存在也可能不存在,但脚本必须检查权限并尽早失败。我找不到一种优雅的方式来实现这一点。这是我尝试过的。
set +e touch $file set -e if [ $? -ne 0 ]; then exit;fi
我为这个脚本保持 set -e
开启,所以如果任何一行有错误,它就会失败。有没有更简单的方法来执行上述脚本?
最佳答案
为什么要复杂化?
file=exists_and_writeable
if [ ! -e "$file" ] ; then
touch "$file"
fi
if [ ! -w "$file" ] ; then
echo cannot write to $file
exit 1
fi
或者,更简洁地说,
( [ -e "$file" ] || touch "$file" ) && [ ! -w "$file" ] && echo cannot write to $file && exit 1
关于linux - bash:文件不存在则创建,否则检查是否可写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4511403/