One common task is checking if a file exists before proceeding with a script. This is useful to prevent errors when attempting to access a file that does not exist.
To check if a file exists in a shell script, we can use the test command with the -e option. The test command is used to evaluate a condition and returns a status code of 0 if the condition is true, and 1 if it is false. The -e option checks if the file exists and returns true if it does.
Here’s an example script that checks if a file named freshers-in.txt exists in the current directory and outputs a message accordingly:
if test -e freshers-in.txt; then
echo "The file exists."
echo "The file does not exist."
Let’s break down how this script works.
The first line #!/bin/bash is called a shebang and specifies which shell should be used to execute the script. In this case, we are using the bash shell.
The if statement checks if the condition inside the parentheses is true. In this case, we are using the test command with the -e option to check if the file freshers-in.txt exists. If it does, the test command returns true, and the if statement executes the code inside the then block.
If the file exists, the script outputs the message “The file exists.” using the echo command. Otherwise, if the test command returns false, the if statement executes the code inside the else block, and the script outputs the message “The file does not exist.” using the echo command.
We can run the script by saving it as a file, for example file-check.sh, and then making it executable using the chmod command:
chmod +x file-check.sh
We can then execute the script by running:
This will output the message “The file does not exist.” if the file freshers-in.txt does not exist, or “The file exists.” if it does.
Checking if a file exists is a common task in shell scripting. We can use the test command with the -e option to check if a file exists, and the if statement to execute code based on the result of the check.
Other urls to refer