Linux Shell Scripting

Linux Shell Scripting Tutorial – Module 6: File Handling in Bash

Module 6: File Handling in Bash

File handling is one of the most important aspects of Bash scripting.
You will learn how to read from files, write to files, append data, and check file existence, permissions, and types.

✅ Writing to a File

  • Use > to overwrite a file.
  • Use >> to append to a file.

#!/bin/bash
echo "This is a new file" > file.txt       # overwrite
echo "This line is appended" >> file.txt  # append
  

✅ Reading from a File

  • Use cat or while read to process files line by line.

#!/bin/bash
# Using cat
cat file.txt

# Using while loop
while read line
do
  echo "Line: $line"
done < file.txt
  

✅ Checking File Existence

  • -e → Check if file exists
  • -f → Check if it is a regular file
  • -d → Check if it is a directory
  • -r, -w, -x → Read, write, execute permissions

#!/bin/bash
file="file.txt"

if [ -e "$file" ]; then
  echo "$file exists."
else
  echo "$file does not exist."
fi

if [ -r "$file" ]; then
  echo "$file is readable"
fi
  

✅ Appending User Input to File


#!/bin/bash
echo "Enter a note:"
read note
echo "$note" >> notes.txt
echo "Note added to notes.txt"
  

✅ Using Here Documents

A Here Document allows writing multiple lines to a file.


#!/bin/bash
cat << EOF > multi.txt
This is line 1
This is line 2
This is line 3
EOF
  

✅ File Manipulation Commands

  • cp source dest → Copy file
  • mv source dest → Move/Rename file
  • rm file → Remove file
  • touch file → Create empty file or update timestamp

✅ Summary

  • Use > and >> for writing and appending files.
  • cat and while read are used for reading files.
  • Check file existence with -e, -f, and -d.
  • Manage file permissions with -r, -w, -x.
  • Here Documents allow writing multiple lines at once.

✅ By the end of this module, you can read, write, append files, and handle file existence checks effectively in your Bash scripts.

Leave a Reply

Your email address will not be published. Required fields are marked *