Skip to content

Latest commit

 

History

History
89 lines (62 loc) · 2.87 KB

File metadata and controls

89 lines (62 loc) · 2.87 KB

File Operations

File operations in shell scripting involve a range of tasks, including reading from and writing to files, managing file permissions, and handling files and directories. This guide explores these aspects to empower you to efficiently work with files in your shell scripts.

Reading from and Writing to Files

Reading from a File

In shell scripting, reading from a file is commonly done using a while read loop. The read command is used to read each line from a file.

#!/bin/bash

# Read content from a file
file_path="example.txt"

while IFS= read -r line; do
  echo "Line: $line"
done < "$file_path"

Here, the while loop iterates over each line in the file specified by file_path, and the content of each line is stored in the variable line.

Writing to a File

Writing to a file is achieved using the echo command and redirection (> or >>). The > operator overwrites the content of the file, while >> appends to it.

#!/bin/bash

# Write content to a file
file_path="output.txt"

echo "Hello, File Operations!" > "$file_path"

In this example, the script writes the message "Hello, File Operations!" to the file specified by file_path.

File Permissions

File permissions in Unix-like systems are crucial for controlling access to files. The chmod command is used to change permissions.

Changing File Permissions

#!/bin/bash

# Change file permissions
file_path="example.txt"

chmod 644 "$file_path"

Here, the chmod 644 command sets read and write permissions for the owner and read-only permissions for others on the file specified by file_path.

File and Directory Handling

Working with files and directories involves tasks such as checking file existence, creating directories, and more.

Checking if a File Exists

You can use the test command or [ ] to check if a file exists.

#!/bin/bash

# Check if a file exists
file_path="example.txt"

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

In this example, the script checks if the file specified by file_path exists.

Creating a Directory

The mkdir command is used to create directories in shell scripting.

#!/bin/bash

# Create a directory
directory_name="new_directory"

mkdir "$directory_name"

Here, the script creates a new directory with the specified name new_directory.

Key Takeaways

  • Reading from and Writing to Files: Use redirection (< and >) or specialized commands (read and echo) to read from and write to files.
  • File Permissions: Use chmod to change file permissions based on your requirements.
  • File and Directory Handling: Utilize commands like test or [ ] to check file existence, and commands like mkdir to create directories.

These examples provide a foundation for performing various file operations in shell scripting. Experiment with different scenarios to enhance your understanding.