检查文件是否可读并且存在于一个 if 条件:if [[ -r -f "/file.png" ] ]]
我正在编写一个 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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
AFAICT,没有办法将它们进一步结合起来。作为可移植性说明,
[[ expr ]]
的可移植性不如[ expr ]
或test expr
。 C 风格的&&
和||
仅包含在 bash 中,因此您可能需要考虑使用 POSIX 语法-a
代表和,-o
代表或。就我个人而言,我更喜欢使用test expr
因为它非常明确。许多 shell(包括 bash)都包含一个内置函数,因此您不必担心进程创建开销。无论如何,我会将您的测试重写为:
该语法将在传统的 Bourne shell、Korn shell 和 Bash 中工作。您也可以使用可移植的
[
语法。AFAICT, there is no way to combine them further. As a portability note,
[[ expr ]]
is less portable than[ expr ]
ortest 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 usingtest 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:
That syntax will work in traditional Bourne shell, Korn shell, and Bash. You can use the
[
syntax portably just as well.是否存在文件可读但它不存在的情况?当可读性会告诉您所需的一切时,不必费心检查是否存在。
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.