Hello, scripters! Today, we're moving on to one of the most common and essential tasks in any scripting language: file manipulation. Almost everything you do on a Linux system involves reading from or writing to a file.
In this tutorial, we'll write two separate scripts to cover two fundamental operations:
- Reading a file specified by the user and displaying its contents to the screen.
- Appending (adding) the contents of one file to the end of another file.
These scripts will teach you about the cat command, file-checking, and the all-important "redirect" operators.
Part 1: Script to Read and Display a File
Our first script will ask the user for a filename, check if that file actually exists, and if it does, print its contents.
The Script: `read_file.sh`
#!/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
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 "-----------------------------------------"
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: Breakdown
read -p "..." filename: Prompts the user and stores their input in thefilenamevariable.if [ -f "$filename" ]; then: This is a crucial test.-fchecks if the path stored in$filename"exists and is a regular file."- We put
"$filename"in quotes to protect against errors if the user enters a filename with spaces.
cat "$filename": Thecat(concatenate) command is the simplest way to read a file and print its contents to standard output (your terminal).else ... fi: If theiftest fails (the file doesn't exist), this block runs, printing our custom error message.
Part 2: Script to Append Content to Another File
This second script will ask for two files: a "source" file and a "destination" file. It will then add the *entire* contents of the source file to the *very end* of the destination file, without deleting anything.
The Script: `append_file.sh`
#!/bin/bash
# This script appends the content of one file to another.
# 1. Ask for the source file
read -p "Enter the source file (to copy FROM): " source_file
# 2. Ask for the destination file
read -p "Enter the destination file (to append TO): " dest_file
# 3. Check if the SOURCE file exists
if [ -f "$source_file" ]; then
# 4. If it exists, append its content to the destination file
cat "$source_file" >> "$dest_file"
echo "-----------------------------------------"
echo "Success: Content of '$source_file' has been appended to '$dest_file'."
else
# 5. If the source file doesn't exist, show an error
echo "Error: Source file '$source_file' not found. No action taken."
fi
How It Works: Breakdown
read -p ...: We get two filenames from the user and store them.if [ -f "$source_file" ]; then: We only need to check if the source file exists. If it doesn't, we have nothing to copy, so we show an error.cat "$source_file" >> "$dest_file": This is the core of the script.cat "$source_file": This reads the source file.>>: This is the append redirect operator. It takes the output from the command on its left (cat) and adds it to the very end of the file on its right ($dest_file).- Note: If
$dest_filedoesn't exist, this command will automatically create it! - Warning: Be careful not to use a single
>. A single>is the overwrite operator and will delete everything in the destination file before writing.
How to Run These Scripts
You can run these scripts using the same standard process.
Step 1: Create the file
Open your terminal and use nano (or any editor) to create your file. Let's use the first script as an example:
nano read_file.sh
Step 2: Paste and Save
Copy the code for the first script and paste it into nano. Press Ctrl+O to save and Ctrl+X to exit.
Step 3: Make it executable
Give the script permission to run:
chmod +x read_file.sh
Step 4: Run it!
Before you run it, you'll need a file to read. Let's make one:
echo "Hello, this is a test file." > my_file.txt
Now, run your script:
$ ./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.
-----------------------------------------
Try running it again with a file that doesn't exist to see your error message in action!
$ ./read_file.sh
Enter the name of the file you want to display: nonexistent_file.txt
Error: File 'nonexistent_file.txt' not found or is not a regular file.
You can follow the exact same steps to test your append_file.sh script.
Challenge Yourself
You've now learned how to check for files, read them, and append to them. Here's a challenge to combine your skills:
Can you modify the append_file.sh script to ask the user, "Are you sure you want to append? (y/n)" and only proceed if they type 'y'?
Happy scripting!

0 Comments