检查文件是否可读并且是否存在于一个 if 条件中: if [[ -r -f "/file.png";]] [英] Checking if a file is readable and exists in one if condition: if [[ -r -f "/file.png" ]]
问题描述
我正在编写一个 if 语句,它通过执行以下操作检查文件是否可读和存在:
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'
推荐答案
AFAICT,没有办法进一步组合它们.作为可移植性说明,[[ expr ]]
的可移植性不如 [ expr ]
或 test expr
.C 风格的 &&
和 ||
仅包含在 bash 中,因此您可能需要考虑使用 -a
的 POSIX 语法and 和 -o
用于 or.就个人而言,我更喜欢使用 test expr
因为它非常明确.许多 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
该语法适用于传统的 Bourne shell、Korn shell 和 Bash.您也可以使用可移植的 [
语法.
That syntax will work in traditional Bourne shell, Korn shell, and Bash. You can use the [
syntax portably just as well.
这篇关于检查文件是否可读并且是否存在于一个 if 条件中: if [[ -r -f "/file.png";]]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!