In my previous blog posts, we covered the basics of using the shell, introduced shell scripting for beginners, and explored advanced techniques and best practices. In this blog post, we will focus on working with files and directories in shell scripts. We will discuss common tasks such as creating, copying, moving, and deleting files and directories, as well as reading and writing to files. We will also provide some resources for further learning.

Creating Files and Directories

To create a new file in a shell script, you can use the touch command:

touch new_file.txt

To create a new directory, you can use the mkdir command:

mkdir new_directory

Copying and Moving Files and Directories

To copy a file, you can use the cp command:

cp source_file.txt destination_file.txt

To copy a directory, you can use the -r (recursive) option:

cp -r source_directory destination_directory

To move a file or directory, you can use the mv command:

mv source_file.txt destination_file.txt

Deleting Files and Directories

To delete a file, you can use the rm command:

rm file_to_delete.txt

To delete a directory, you can use the -r (recursive) option:

rm -r directory_to_delete

Reading and Writing to Files

To read the contents of a file, you can use the cat command:

cat file_to_read.txt

To write to a file, you can use the > operator to overwrite the file or the >> operator to append to the file:

echo "This is a new line" > file_to_write.txt
echo "This is another new line" >> file_to_write.txt

To read a file line by line, you can use a while loop with the read command:

#!/bin/bash

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

Searching for Files and Directories

To search for files and directories, you can use the find command:

find /path/to/search -name "file_pattern"

For example, to find all .txt files in the /home/user directory, you can use:

find /home/user -name "*.txt"

Resources

To further improve your skills in working with files and directories in shell scripts, here are some resources:

In conclusion, working with files and directories is an essential aspect of shell scripting. By mastering common tasks such as creating, copying, moving, and deleting files and directories, as well as reading and writing to files, you will be well-equipped to handle a wide range of shell scripting tasks.