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

发布于 2024-10-11 12:10:16 字数 423 浏览 6 评论 0 原文

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

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

然后我想,你当然可以使这个更小,可能像这样:

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

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

./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'

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

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'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

物价感观 2024-10-18 12:10:17

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

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

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

该语法将在传统的 Bourne shell、Korn shell 和 Bash 中工作。您也可以使用可移植的 [ 语法。

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 -a for and and -o for or. Personally, I prefer using test expr since it is very explicit. Many shells (bash included) include a builtin for it so you do not have to worry about process creation overhead.

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.

鱼窥荷 2024-10-18 12:10:17

是否存在文件可读但它不存在的情况?当可读性会告诉您所需的一切时,不必费心检查是否存在。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文