Exploring Bash — Part 10

Dineshkumaar R
7 min readApr 17, 2024

--

Introduction

Hey Friends, Welcome back to my Bash exploration blog series! Let’s dive right in! File operations involve actions performed on files and directories, including reading, writing, copying, moving, and deleting. In Bash scripting, file operations are essential for managing data and interacting with the filesystem efficiently.

File Existence

Checking the existence of files and directories is crucial for handling file operations in Bash scripts. Conditional statements and file test operators (-e, -f, -d, -s) are commonly used to check file existence and properties.

#!/bin/bash

# Prompt the user to enter a file name
read -p "Enter a file name: " file_name

# Check if the file exists
if [ -e "$file_name" ]; then
echo "$file_name exists."

# Check if the file is a regular file
if [ -f "$file_name" ]; then
echo "$file_name is a regular file."
else
echo "$file_name is not a regular file."
fi

# Check if the file is a directory
if [ -d "$file_name" ]; then
echo "$file_name is a directory."
else
echo "$file_name is not a directory."
fi

# Check if the file is not empty
if [ -s "$file_name" ]; then
echo "$file_name is not empty."
else
echo "$file_name is empty."
fi

else
echo "$file_name does not exist."
fi

• The script prompts the user to enter a file name.
• It first checks if the file exists using the -e operator.
• If the file exists, it performs additional checks:
-Uses -f to check if it’s a regular file.
-Uses -d to check if it’s a directory.
-Uses -s to check if the file is not empty.
• Finally, it prints appropriate messages based on the results of these checks.
• If the file does not exist, it notifies the user accordingly.

File Creation and Writing

Creating and writing to files in Bash can be accomplished using redirection (‘>’ and ‘>>’ operators) and the ‘echo’ command.

#!/bin/bash

echo "Bash Learning" > example.txt # example.txt file created and added first line
echo "I have created and written the first line in the example.txt file." > example.txt # Overwrites file
echo "Add something in the next line" >> example.txt # Appends to file

1. echo “Bash Learning” > example.txt:
— This command creates a new file named `example.txt` if it doesn’t exist, and writes the string “Bash Learning” to it.
— The `>` redirection operator is used to redirect the output of the `echo` command to the file `example.txt`. If `example.txt` already exists, this operation will overwrite its contents.

2. echo “I have created and written the first line in the example.txt file.” > example.txt:
— This command again writes a string to the file `example.txt`.
— Since it uses the `>` redirection operator, it will overwrite the existing content of `example.txt` with the new string.
— Therefore, the first line written in the previous step will be replaced by this new line.

3. echo “Add something in the next line” >> example.txt:
— This command appends the string “Add something in the next line” to the end of the file `example.txt`.
— The `>>` redirection operator is used to append the output of the `echo` command to the file `example.txt`. Therefore, the new string will be added as a new line at the end of the file, preserving the existing content.

File Reading

Reading data from files in Bash can be done using redirection (‘<’ operator) and commands like ‘cat’, ‘head’, ‘tail’, and ‘read’.

#!/bin/bash

# Create a file with some content
echo "I am Learning Bash Scripting" > example.txt
echo "It's very easy to understand" >> example.txt

# Method 1: Using redirection (< operator) and the read command
echo "Method 1: Using redirection (< operator) and the read command"
while IFS= read -r line; do
echo "$line"
done < example.txt
echo

# Method 2: Using cat command
echo "Method 2: Using cat command"
cat example.txt
echo

# Method 3: Using head command
echo "Method 3: Using head command"
head example.txt
echo

# Method 4: Using tail command
echo "Method 4: Using tail command"
tail example.txt
echo

Method 1: Uses redirection (< operator) to read from the file example.txt and the read command in a loop to read each line one by one.
Method 2: Uses the cat command to display the entire contents of the file example.txt.
Method 3: Uses the head command to display the first few lines (by default, 10 lines) of the file example.txt.
Method 4: Uses the tail command to display the last few lines (by default, 10 lines) of the file example.txt.

File Permissions

Understanding and managing file permissions and ownership are crucial aspects of file operations in Unix/Linux filesystems. The ‘chmod’ command is commonly used to view and modify file permissions.

chmod +x script.sh  # Adds execute permission
chmod 644 file.txt # Sets read/write for owner, read for group and others

File Manipulation

Manipulating files, such as copying, moving, and deleting, is a common task in Bash scripting. Commands like ‘cp’, ‘mv’, and ‘rm’ are used for these operations.

# Copying a file
cp source.txt destination.txt

# Moving a file
mv source.txt new_location/

# Deleting a file
rm file.txt

1. Copying a file (‘cp source.txt destination.txt’):
— This command copies the contents of the file ‘source.txt’ to a new file named ‘destination.txt’.
— If ‘destination.txt’ already exists, it will be overwritten with the contents of ‘source.txt’.
— If ‘destination.txt’ does not exist, it will be created with the contents of ‘source.txt’.

2. Moving a file (‘mv source.txt new_location/’):
— This command moves the file ‘source.txt’ to the directory specified by ‘new_location/’.
— If ‘new_location/’ is a directory, ‘source.txt’ will be moved into that directory.
— If ‘new_location/’ is a file, ‘source.txt’ will be renamed to ‘new_location’.
— If ‘source.txt’ and ‘new_location’ are on different filesystems, ‘mv’ will copy the file and then delete the original.

3. Deleting a file (‘rm file.txt’):
— This command deletes the file ‘file.txt’ from the filesystem permanently.
— There is no way to undo the deletion performed by ‘rm’.
— To delete multiple files at once, you can provide multiple filenames separated by spaces: ‘rm file1.txt file2.txt’.
— To delete a directory and its contents recursively, you can use the ‘-r’ flag: ‘rm -r directory/’.

File Searching

Searching for files and directories based on specific criteria is a common requirement in Bash scripting. Commands like ‘find’ and ‘grep’ are used for file searching.

# Finding files by name
find . -name "*.txt"

# Searching for text within files
grep "password" file.txt

The command ‘ find . -name “*.txt” ’ is used to find files with the ‘.txt’ extension in the current directory and its subdirectories. Here’s how it works:
- ‘find’ : This command is used to search for files and directories within a specified directory hierarchy.
- ‘.’ : Specifies the starting directory for the search. In this case, ‘.’ represents the current directory.
- ‘-name “*.txt” ’ : This option tells ‘find’ to search for files whose names match the pattern ‘“*.txt”’. The asterisk ‘*’ is a wildcard that matches any sequence of characters, and ‘“*.txt”’ specifies that the file names must end with ‘.txt’.

The command ‘grep “password” file.txt’ is used to search for a specific pattern of text within a file. Here’s how it works:
- ‘grep’: This command is used to search for text patterns within files.
- ‘ “password” ’: Specifies the pattern of text to search for within the file. In this case, it’s searching for the word “password”
- ‘file.txt’: Specifies the name of the file in which to search for the pattern.

File System Information

Retrieving information about the filesystem, such as disk usage and block devices, can be useful for system administration tasks. Commands like ‘df’, ‘du’, and ‘lsblk’ provide filesystem information.

# Displaying disk usage
df -h

# Displaying disk usage of specific directory
du -h directory_name

# Displaying block device information
lsblk

Summary of the blog

1. File Existence: Checking file existence and properties using conditional statements and file test operators like ‘-e’, ‘-f’, ‘-d’, ‘-s’.
2. File Creation and Writing: Creating and writing to files using redirection (‘>‘, ‘>>‘) and the ‘echo’ command.
3. File Reading: Reading data from files using redirection (‘<‘) and commands like ‘cat’, ‘head’, ‘tail’, and ‘read’.
4. File Permissions: Managing file permissions using the ‘chmod’ command.
5. File Manipulation: Manipulating files with commands like ‘cp’, ‘mv’, and ‘rm’.
6. File Searching: Finding files by name using ‘find’ and searching for text within files using ‘grep’.
7. File System Information: Retrieving information about the filesystem using commands like ‘df’, ‘du’, and ‘lsblk’.

URL’s :

  1. Exploring bash — Part1 : https://medium.com/@dineshkumaar478/exploring-bash-part-1-3dabf4b5ef9e
  2. Exploring bash — Part2 : https://medium.com/@dineshkumaar478/exploring-bash-part-2-71f341fb5700
  3. Exploring bash — Part3 : https://medium.com/@dineshkumaar478/exploring-bash-part-3-db1fc958eb17
  4. Exploring bash — Part4 : https://medium.com/@dineshkumaar478/exploring-bash-part-4-4521aaac30ea
  5. Exploring bash — Part5 : https://medium.com/@dineshkumaar478/exploring-bash-part-5-a136eb036b4f
  6. Exploring bash — Part6 : https://medium.com/@dineshkumaar478/exploring-bash-part-6-31887f5c3695
  7. Exploring bash — Part7 : https://medium.com/@dineshkumaar478/exploring-bash-part-7-f9a3e37a5931
  8. Exploring bash — Part8 : https://medium.com/@dineshkumaar478/exploring-bash-part-8-fa6fbb538d3a
  9. Exploring bash — Part9 : https://medium.com/@dineshkumaar478/exploring-bash-part-9-99cf7eca0190

Thank you for taking the time to read my blog. Wishing you a joyful learning experience ahead!

--

--

Dineshkumaar R

🔐 Cyber Security Engineer | Penetration Tester | VAPT Specialist | 🚩 Hackthebox (Pro Hacker) | 🏆 Tryhackme (Guru)