bash 检查文件是否可读并存在于一个 if 条件中:if [[ -r -f "/file.png" ]]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4653829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:04:00  来源:igfitidea点击:

Checking if a file is readable and exists in one if condition: if [[ -r -f "/file.png" ]]

bashif-statementdebian

提问by Mint

I was writing an if statement which checked if a file is readable and exists by doing the following:

我正在编写一个 if 语句,通过执行以下操作来检查文件是否可读和存在:

if [[ -r "$upFN" && -f "$upFN" ]]; then
....
fi

Then I thought, surly you can make this smaller, something maybe like this:

然后我想,当然你可以把它变小,可能是这样的:

if [[ -r -f "$upFN" ]]; then
....
fi

But this doesn't work, it returns errors:

但这不起作用,它返回错误:

./ftp.sh: line 72: syntax error in conditional expression
./ftp.sh: line 72: syntax error near `"$upFN"'
./ftp.sh: line 72: `if [[ -r -f "$upFN" ]]; then'

回答by D.Shawley

AFAICT, there is no way to combine them further. As a portability note, [[ expr ]]is less portable than [ expr ]or test expr. The C-style &&and ||are only included in bash so you might want to consider using the POSIX syntax of -afor andand -ofor or. Personally, I prefer using test exprsince it is very explicit. Many shells (bash included) include a builtin for it so you do not have to worry about process creation overhead.

AFAICT,没有办法将它们进一步结合起来。作为便携性说明,[[ expr ]]不如[ expr ]或便携test expr。C 风格的&&and||仅包含在 bash 中,因此您可能需要考虑使用-afor and-ofor or的 POSIX 语法。就个人而言,我更喜欢使用,test expr因为它非常明确。许多 shell(包括 bash)都包含一个内置函数,因此您不必担心进程创建开销。

In any case, I would rewrite your test as:

无论如何,我会将您的测试重写为:

if test -r "$upFN" -a -f "$upFN"
then
  ...
fi

That syntax will work in traditional Bourne shell, Korn shell, and Bash. You can use the [syntax portably just as well.

该语法适用于传统的 Bourne shell、Korn shell 和 Bash。您也可以[便携地使用该语法。

回答by Rob Kennedy

Is there ever a case where a file would be readable but it doesn'texist? Don't bother checking for existence when readability will tell you all you need.

是否有文件可读但存在的情况?当可读性会告诉你所有你需要的时候,不要费心检查是否存在。