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'
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.
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.
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 ...
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With