在我的shell脚本中,我正在尝试检查特定文件是否存在以及是否具有读取权限。
我的文件路径中包含空格。
我将文件路径加上引号:
虽然文件确实存在,但当我尝试使用“cat $file”读取它时,出现了权限错误。我做错了什么?
我的文件路径中包含空格。
我将文件路径加上引号:
file='/my/path/with\ some\ \spaces/file.txt'
这是用于检查文件是否存在的函数:
#Check if file exists and is readable
checkIfFileExists() {
#Check if file exists
if ! [ -e $1 ]; then
error "$1 does not exists";
fi
#Check if file permissions allow reading
if ! [ -r $1 ]; then
error "$1 does not allow reading, please set the file permissions";
fi
}
在这里我使用双引号以确保将文件作为一个参数传递:
checkIfFileExists "'$file'";
我从bash中收到一个错误信息:
[: too many arguments
我认为它不能将其作为一个参数。
但是在我的自定义错误中,我获取了整个路径,并且它说不存在。
Error: '/my/path/with\ some\ \spaces/file.txt' does not exists
虽然文件确实存在,但当我尝试使用“cat $file”读取它时,出现了权限错误。我做错了什么?
[ ! -r "$1" ] && some command || other command
代替完整的if [..]; then some command; else other command; fi
-- 但无论哪种情况下都要引用你的变量。 - David C. Rankin