【发布时间】:2015-11-23 08:31:11
【问题描述】:
在我的 shell 脚本中,我正在尝试检查特定文件是否存在以及它是否具有读取权限。
我的文件路径中有空格。
我引用了文件路径:
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——但在任何一种情况下都要引用您的变量。