检查文件是否可读存在于一个,如果条件:如果[-r -f" /file.png" ]] [英] Checking if a file is readable and exists in one if condition: if [[ -r -f "/file.png" ]]
问题描述
我在写一个if语句检查它如果文件是可读且通过执行以下操作存在:
如果[-r$ upFN&放大器;&安培; -f$ upFN]];然后
....
科幻
后来我想,粗暴可以让这个更小的东西,也许是这样的:
如果[-r -f$ upFN]];然后
....
科幻
但是,这并不工作,它会返回错误:
./ ftp.sh:行72:在条件前pression语法错误
./ftp.sh:线路72:语法错误附近'$ upFN'
./ftp.sh:线路72:`如果[-r -f$ upFN]];然后'
AFAICT,没有办法将它们进一步结合起来。作为便携笔记, [EXPR]
比便携式少[EXPR]
或测试EXPR
。 C风格的&放大器;&安培;
和 ||
只包含在bash,所以你可能要考虑使用 -a
为POSIX语法的和和 -o
为或。就个人而言,我使用测试EXPR
,因为它是非常明确的preFER。许多shell(包括bash)的包括它内置,所以你不必担心进程创建开销。
在任何情况下,我会重写你的测试为:
如果测试-r$ upFN-a -f$ upFN
然后
...
科幻
这是语法将在传统的Bourne shell,Korn shell程序和Bash工作。您可以使用 [
语法可移植一样好。
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, 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.
这篇关于检查文件是否可读存在于一个,如果条件:如果[-r -f" /file.png" ]]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!