Linux and Command-Line Basics

if [ -f "$f" ]; then
  echo "found"
fi

In a shell script, in which of the following cases is the condition of the if above true?

  1. AWhen a regular file with the name in variable f exists
  2. BWhen a file with the name in variable f exists and its size is greater than 0
  3. 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.
Practice this topic Back to topic

Books on Linux and Command-Line Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More Linux and Command-Line Basics questions

  1. Which of the following are the files in the directory after the session above?
  2. An executable script run.sh in the current directory gives "command not found" when run by typing "run.sh", but runs when typed as "./run.sh". Which of the following is the reason?
  3. When the commands above are run in order, which of the following is the pair of outputs of the two bash -c commands?
  4. Which of the following is the main function of a Linux package management system (apt on Debian-based systems, dnf on Red Hat-based systems and so on)?
  5. On a Linux system using systemd, which of the following is the difference between "systemctl start license.service" and "systemctl enable license.service" for the service license.service?