Linux and Command-Line Basics
if [ -f "$f" ]; then
echo "found"
fiIn a shell script, in which of the following cases is the condition of the if above true?
- AWhen a regular file with the name in variable f exists
- BWhen a file with the name in variable f exists and its size is greater than 0
- CWhen a file or a directory with the name in variable f exists
Show answer and explanation
Answer: A. When a regular file with the name in variable f exists
[ ] is another way of writing the test command: it returns exit status 0 (true) if the condition holds, and if branches on that. -f checks that "a regular file with that name exists" and is false for a directory. To check only existence, use -e; to check for a directory, -d; and to check that the size is greater than 0, -s. A space is required after [ and before ], and enclosing the variable in double quotes, as in "$f", makes the test work correctly even for names containing spaces.
- A. Correct. -f is true when a regular file exists, even if it is empty.
- B. Checking that the size is greater than 0 as well is -s. -f is true even for an empty file.
- C. Checking existence regardless of file or directory is -e. -f is false for a directory.