Shell Scripting : How to Read and Display a File's Content

Hello, scripters! Welcome to another foundational tutorial in our shell scripting series. One of the most common tasks you'll ever perform in a script is reading data from a file. This could be for checking logs, processing data, or just displaying information.

Today, we're going to write a simple, safe, and useful script that does just that: it will ask the user for a filename, check if that file actually exists, and if it does, print all of its contents to the screen.

How to Read and Display a File's Content

Let's get started!

The Shell Script

Here is the complete, commented script. We're using the cat command, which is the simplest and most direct way to display a file's contents.

#!/bin/bash

# This script reads and displays the content of a file.

# 1. Ask the user for the filename
read -p "Enter the name of the file you want to display: " filename

# 2. Check if the file exists and is a regular file
#    This is an important safety check!
if [ -f "$filename" ]; then

    # 3. If it exists, print a header and then the file's content
    echo "-----------------------------------------"
    echo "Displaying content of '$filename':"
    echo "-----------------------------------------"
    
    cat "$filename"
    
    echo "-----------------------------------------"
    echo "End of file."

else
    # 4. If it doesn't exist, show an error message
    echo "Error: File '$filename' not found or is not a regular file."
fi

How It Works: A Step-by-Step Breakdown

Let's break down the logic of this script.

  • #!/bin/bash
    The "shebang." This must be the very first line. It tells your system to use the bash shell to run the script.

  • read -p "..." filename
    This command prints a prompt (-p) with the text in quotes and then waits for the user to type something. Whatever the user types is stored in the filename variable.

  • if [ -f "$filename" ]; then
    This is our crucial safety check.
    • if [ ... ]: This is a "test" command.
    • -f: This is a test operator that checks if the path stored in $filename "exists and is a regular file."
    • "$filename": We use quotes around the variable to prevent errors in case the user enters a filename with spaces (e.g., "my test file.txt").

  • cat "$filename"
    This is the core command. cat (short for "concatenate") reads one or more files and prints their contents to the terminal. It's the simplest way to display a file.

  • else
    This block of code runs only if the if test fails (meaning the file was not found).

  • echo "Error: ..."
    Prints our user-friendly error message so the user knows what went wrong.

  • fi
    This signals the end of the if/else block (it's "if" spelled backward).

How to Run Your Script

Let's test our new script. First, we need a file to read.

Step 1: Create a test file
In your terminal, run this command to create a simple text file:

echo "Hello, this is a test file." > my_file.txt
echo "It has two lines." >> my_file.txt

Step 2: Create the script file
Use nano (or any text editor) to create your file:

nano read_file.sh

Step 3: Paste and Save
Copy the script from the top of this post, paste it into nano, and save/exit (Ctrl+O, Enter, Ctrl+X).

Step 4: Make it executable
Give the script permission to run:

chmod +x read_file.sh

Step 5: Run it! (Two Tests)
First, let's test the "success" case by giving it the file we created:

$ ./read_file.sh
Enter the name of the file you want to display: my_file.txt
-----------------------------------------
Displaying content of 'my_file.txt':
-----------------------------------------
Hello, this is a test file.
It has two lines.
-----------------------------------------
End of file.

Now, let's test the "error" case by giving it a file that doesn't exist:

$ ./read_file.sh
Enter the name of the file you want to display: nonexistent.txt
Error: File 'nonexistent.txt' not found or is not a regular file.

Challenge Yourself

Great job! You've learned how to read user input, check for files, and display their contents.
Want a challenge? Try modifying this script to also count the number of lines in the file and display that count. (Hint: The command wc -l counts lines, and you can pipe cat to it: cat filename | wc -l).

Happy scripting!

Post a Comment

0 Comments