Here are the simple bash script that reads a file name from the user and displays its contents on the terminal:
1. Create a new file as mentioned below.
vi display_file.sh
2. Copy and paste below simple bash script that prompts the user for a file name, reads the contents of the specified file, and displays them on the terminal.
#!/bin/bash # Prompt the user for a file name echo "Enter the name of the file:" read filename # Check if the file exists if [ -e "$filename" ]; then # Display the contents of the file echo "*******Contents of $filename:*************" cat "$filename" else # If the file does not exist, display an error message echo "Error: File '$filename' not found." fi
Now, let’s break down the script:
A] Shebang (#!/bin/bash):
– This line indicates that the script should be executed using the Bash shell.
B] Prompt for User Input:
– echo “Enter the name of the file:” prompts the user to enter a filename.
– read filename reads the user’s input and stores it in the variable filename.
C] Check if File Exists:
– if [ -e “$filename” ]; then checks if the file specified by the user exists.
– -e is a test condition that checks if a file exists.
D] Display File Contents:
– echo “Contents of $filename:” prints a message indicating that the following lines will display the file contents.
– cat “$filename” displays the contents of the file.
E] Handle Non-Existent File:
– else is part of the conditional statement and is executed if the file does not exist.
– echo “Error: File ‘$filename’ not found.” displays an error message.
3. Save and close the “vi” editor by pressing “Esc” key and type :wq! and press “enter” key.
4. Make sure to give execute permissions to the script before running it. You can do this by running the following command in the terminal:
chmod +x display_file.sh
Note :
- Replace “display_file.sh” with the actual name you save the script as.
- You have to enter the exact file name as linux uses case sensitive.
The script will prompt you to enter a filename, and it will then display the contents of the specified file if it exists.
Click Here!!! to write a bash script that checks if a file exists in specific folder or directory.
How do you feel about this post? Drop your comments below..