【问题标题】:Shell Script check if file exists, and has read permissionsShell 脚本检查文件是否存在,并具有读取权限
【发布时间】: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——但在任何一种情况下都要引用您的变量。

标签: bash shell


【解决方案1】:

当您需要变量插值时,正确的引用方式是使用双引号:

if [ -e "$1" ]; then

您需要在整个脚本中进行类似的引用,并且调用者需要引用或转义字符串——但不能同时使用两者。分配时,请使用以下之一:

file='/my/path/with some spaces/file.txt'
# or
file=/my/path/with\ some\ spaces/file.txt
# or
file="/my/path/with some spaces/file.txt"

然后在值周围使用双引号将其作为单个参数传递:

checkIfFileExists "$file"

同样,如果您需要对变量的值进行插值,请使用双引号。

要快速了解这些引号的作用,请尝试以下操作:

vnix$ printf '<<%s>>\n' "foo bar" "'baz quux'" '"ick poo"' \"ick poo\" ick\ poo
<<foo bar>>
<<'baz quux'>>
<<"ick poo">>
<<"ick>>
<<poo">>
<<ick poo>>

此外,另请参阅When to wrap quotes around a shell variable?

【讨论】:

  • 明白了,这很有意义..现在看起来确实将它作为一个整体..尽管文件存在,但 -e 返回 false 是否有原因?我知道它存在并且权限不好..如果我试图打开它 - 它告诉我它可以因为权限
  • 我认为这是因为我的路径中有转义\..可能吗?
  • 啊,是的;引用 转义空格,但不能同时转义。我会再更新一些答案。
【解决方案2】:
if [[ -e $1 ]];then
 echo it exists
else
 echo it doesnt
fi

if [[ -r $1 ]];then
  echo readable
else
  echo not readable
fi

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 2011-04-20
    • 2017-09-11
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多