Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'
like image 475
Mint Avatar asked Jan 11 '11 03:01

Mint


People also ask

How to check if a file is readable in Java?

Java 7 introduced the Files.isReadable static method, it accepts a file Path and returns true if file exists and is readable, otherwise false. Tests whether a file is readable. This method checks that a file exists and that this Java virtual machine has appropriate privileges that would allow it open the file for reading.

How to check the readability of a file?

It can be useful to check the readability of the file at server startup and WARN if it's not readable. Then somebody can fix the situation (make the file readable, anything) before the circumstances actually causes the subcomponent to try to read that file.

How to check if file can be read or written in Python?

Python How to Check if File can be Read or Written 1 Introduction#N#It can be a bit cumbersome at times to check for read or write permission on a file. The check might... 2 Check if File can be Read#N#A file can be read if it exists and has read permission for the user. Attempting to open... 3 Checking if file can be written More ...

How to check if a file can be written?

Checking if file can be written Check for file-write is a little bit different from checking readability. If the file does not exist, we need to check the parent directory for write permission. 3.1. Attempt to Write File


1 Answers

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.

like image 160
D.Shawley Avatar answered Sep 28 '22 15:09

D.Shawley