0

I found this bash script (which works). This script plays an important role. The whole code quality of the script is good. I'm just wondering if there's any sense at the following construction?

if [ "${G_FILE}" != "" ] && [ -f "${G_FILE}" ] && [ -r "${G_FILE}" ]; then
....

The manual says:

[ -f FILE ] True if FILE exists and is a regular file.
[ -r FILE ] True if FILE exists and is readable.
[ STRING1 != STRING2 ]  True if the strings are not equal.

My thoughts:

  1. [ -n "${G_FILE}" ] or [ "${G_FILE}" ] should be instead of [ "${G_FILE}" != "" ].
  2. Only [ -r "${G_FILE}" ] will do the same.

Am I right?

2 Answers 2

3

First, [ only makes sense over [[ to begin with if you require strict POSIX conformance. -f and -r tests should always be false if empty provided their option arguments are properly quoted, so the first test is useless. -r will be true for e.g. named pipes, sockets, etc. -f restricts things to regular files only.

Typically, you don't need to check that a file is actually readable. That check can just be bundled in with a test for whether the thing that's using the file was successful most of the time. A failed redirect is false, and it is better to write functions in a way that return an appropriate status upon failure than to test for a readable file first.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the good explanation. [] and [[]] is important too, there are lots of materials and discussions. I'm on my way to read them. For someone, how is interested too
2

Unless you specifically require it to be a regular file, using only -r is enough.

3 Comments

Indeed, without the -f, directories would pass, too.
This will prevent you from using sockets, FIFOs, devices, etc. as sources. If you want to specifically prevent directories then you should use ! -d instead of -f.
In this case a regular file is exactly what I need: read some parameters from a file. I could left it without editing, but I was interested about the sense of this expression for the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.