Linux Bash Script Check File Existence

‮ttual.www‬uri.com
Linux Bash Script Check File Existence

To check if a file exists in a Linux bash script, you can use the test command with the -f option. The test command is a built-in command that evaluates an expression and returns a exit status of 0 (true) or 1 (false).

For example, to check if the file /tmp/file.txt exists, you can use the following command:

if test -f /tmp/file.txt; then
  echo "File exists"
else
  echo "File does not exist"
fi

This will output "File exists" if the file exists, or "File does not exist" if the file does not exist.

You can also use the [ command, which is an alias for the test command, to check for file existence. For example:

if [ -f /tmp/file.txt ]; then
  echo "File exists"
else
  echo "File does not exist"
fi

This will have the same effect as the previous example.

You can also use the if statement with the -f operator to check for file existence. For example:

if [ -f /tmp/file.txt ]; then
  echo "File exists"
else
  echo "File does not exist"
fi

This will also have the same effect as the previous examples.

It is important to note that the test command and the [ command are not the same as the if statement. The test command and the [ command evaluate an expression and return a exit status, while the if statement is used to execute a command based on the exit status of a command or an expression.

Created Time:2017-10-29 22:08:51  Author:lautturi