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

前端 未结 2 1907
死守一世寂寞
死守一世寂寞 2021-02-20 17:47

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
         


        
相关标签:
2条回答
  • 2021-02-20 18:02

    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.

    0 讨论(0)
  • 2021-02-20 18:08

    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.

    0 讨论(0)
提交回复
热议问题