File Operations in Shell Scripting
This tutorial provides a comprehensive guide to performing file operations in shell scripts. File operations are a fundamental part of shell scripting and are essential for automating tasks related to file handling.
1. Creating Files
To create a file, use the touch
command:
touch filename.txt
This command creates an empty file named "filename.txt".
2. Writing to Files
You can write to a file using redirection operators. Here are a few examples:
To write a single line to a file, use the >
operator:
echo "Hello, World!" > filename.txt
This command writes "Hello, World!" to "filename.txt". If the file already exists, it will be overwritten.
To append a line to a file, use the >>
operator:
echo "This is a new line." >> filename.txt
This command appends "This is a new line." to "filename.txt".
3. Reading from Files
You can read the contents of a file using the cat
command:
cat filename.txt
This command displays the contents of "filename.txt".
To read the file line by line, you can use a while loop:
while IFS= read -r line; do
echo "$line"
done < filename.txt
4. Copying Files
To copy a file, use the cp
command:
cp source.txt destination.txt
This command copies "source.txt" to "destination.txt".
5. Moving Files
To move a file, use the mv
command:
mv oldname.txt newname.txt
This command renames "oldname.txt" to "newname.txt".
You can also use the mv
command to move a file to a different directory:
mv filename.txt /path/to/directory/
This command moves "filename.txt" to the specified directory.
6. Deleting Files
To delete a file, use the rm
command:
rm filename.txt
This command deletes "filename.txt".
To delete multiple files, you can specify multiple filenames:
rm file1.txt file2.txt file3.txt
This command deletes "file1.txt", "file2.txt", and "file3.txt".
7. Checking File Existence
You can check if a file exists using the -e
option in a conditional statement:
if [ -e filename.txt ]; then
echo "File exists."
else
echo "File does not exist."
fi
8. File Permissions
To change file permissions, use the chmod
command. Here are a few examples:
To make a file readable and writable by the owner only:
chmod 600 filename.txt
To make a file readable and writable by the owner and the group:
chmod 660 filename.txt
To make a file readable, writable, and executable by everyone:
chmod 777 filename.txt
9. Conclusion
In this tutorial, you learned various file operations in shell scripting, including creating, writing, reading, copying, moving, deleting, checking existence, and changing permissions. These operations are essential for managing files efficiently in your shell scripts.