Working with Files and Directories

Section 4: Working with Files and Directories

Lesson 1: File and Directory Manipulation

File and directory manipulation in shell scripts involves various operations such as checking existence, handling types, and managing their creation, movement, and deletion.

1.1 Checking File Existence and Types

#!/bin/bash

# Checking file existence and types


file_path="example.txt"


# Check if the file exists

if [ -e "$file_path" ]; then

    echo "File exists."

    

    # Check if it's a regular file

    if [ -f "$file_path" ]; then

        echo "It's a regular file."

    fi

    

    # Check if it's a directory

    if [ -d "$file_path" ]; then

        echo "It's a directory."

    fi

else

    echo "File does not exist."

fi

1.2 Creating, Moving, and Deleting Files and Directories 

#!/bin/bash

# File and directory manipulation


# Create a directory

mkdir my_directory


# Create a file

echo "This is a sample file." > my_file.txt


# Move a file to a directory

mv my_file.txt my_directory/


# Rename a file

mv my_directory/my_file.txt my_directory/new_file.txt


# Remove a file

rm my_directory/new_file.txt


# Remove a directory

rmdir my_directory


Lesson 2: File Permissions and Ownership

Shell scripts can handle file permissions and ownership, ensuring secure file management.

2.1 Changing File Permissions

#!/bin/bash

# Changing file permissions


file_path="example.txt"


# Give read, write, and execute permissions to the owner

chmod u+rwx "$file_path"


# Give read and execute permissions to the group

chmod g+rx "$file_path"


# Give read-only permission to others

chmod o+r "$file_path"

2.2 Modifying File Ownership 

#!/bin/bash

# Modifying file ownership


file_path="example.txt"


# Change the owner to user "john"

chown john "$file_path"


# Change the group to group "staff"

chgrp staff "$file_path"

Understanding how to manipulate files and directories, as well as manage permissions and ownership, is crucial for effective shell scripting. In the upcoming sections, we'll explore more advanced scripting techniques and real-world applications.