Shell script that verifies if a file exists or not

In this following post, you will learn how to write a simple shell script that verifies if a file exists or not and whether it’s a directory or a regular file.

1. Create a new file as mentioned below.
vi check_file.sh

2. Below is a simple shell script that verifies if a file exists and determines whether it’s a directory or a regular file. The script uses the “test” command along with the “-e”, “-d”, and “-f” flags for existence, directory, and regular file checks, respectively.

#!/bin/bash

# Prompt user for the file path

echo -n "Enter the path of the file or directory: "

read file_path

# Check if the file or directory exists

if [ -e "$file_path" ]; then

# Check if it's a directory

if [ -d "$file_path" ]; then

echo "The path '$file_path' exists and is a directory."

# Check if it's a regular file

elif [ -f "$file_path" ]; then

echo "The path '$file_path' exists and is a regular file."

else

echo "The path '$file_path' exists but is neither a directory nor a regular file."

fi

else

echo "The path '$file_path' does not exist."

fi

Now, let’s break down the script:

1. “#!/bin/bash”: This line is known as a shebang and specifies the shell to be used for executing the script. In this case, it’s Bash.

2. “echo -n “Enter the path of the file or directory: “”: This line prompts the user to enter the file or directory path, and the “-n” flag ensures that the cursor stays on the same line after the user input.

3. “read file_path”: Reads the user input and stores it in the variable “file_path”.

4. “if [ -e “$file_path” ]; then”: Checks if the file or directory specified by “$file_path” exists.

5. “if [ -d “$file_path” ]; then”: Checks if the path is a directory.

6. “elif [ -f “$file_path” ]; then”: Checks if the path is a regular file.

7. “else”: If it’s not a directory or a regular file, it prints that the path is neither.

8. “fi”: Ends the if-else block.

9. If the path doesn’t exist (“else” branch of the outer “if”), it prints that the path does not exist.

You can save this script in a file with a “.sh” extension (e.g., “check_file.sh”), make it executable (“chmod +x check_file.sh”), and then run it from the terminal.


Note : Replace “check_file.sh” with the actual name you save the script as.

The script will prompt you to enter a filename, and it will then display the contents of the specified file if it exists.

How do you feel about this post? Drop your comments below..