Handling Files and Directories in Scripts

Create, delete, copy, move files with shell.

Working with files and directories is a fundamental part of any scripting language, especially when using the shell. Shell scripts can automate common file operations—such as creating, deleting, copying, and moving files and directories—making your workflow more efficient and reliable. This guide will walk you through key file and directory operations in shell scripts, illustrating each with practical examples.


1. Creating Files and Directories

Creating a File

To create an empty file, use the touch command:

touch myfile.txt

Alternatively, to create a file and add content:

echo "Hello World!" > greetings.txt

Creating a Directory

The mkdir command is used for directories:

mkdir myfolder

To create parent directories if they don’t exist, use the -p flag:

mkdir -p path/to/newfolder

2. Deleting Files and Directories

Deleting a File

To remove a file:

rm myfile.txt

Deleting a Directory

Use rm -r for directories (recursive deletion):

rm -r myfolder

For an empty directory, you can also use:

rmdir emptyfolder

3. Copying Files and Directories

Copying a File

The cp command copies files:

cp original.txt copy.txt

Copying Multiple Files

To copy multiple files into a directory:

cp file1.txt file2.txt destination_folder/

Copying Directories

Copy directories recursively with -r:

cp -r sourcedir targetdir

4. Moving and Renaming Files and Directories

Shell uses the mv command for moving and renaming.

Move a File to Another Directory

mv file.txt backup/

Rename a File

mv oldname.txt newname.txt

Move or Rename Directories

mv oldfolder/ newfolder/

5. Checking Existence Before Operations

Before performing operations, check if files or directories exist to avoid errors.

Check if a File Exists

if [ -f "myfile.txt" ]; then
  echo "File exists."
else
  echo "File does not exist."
fi

Check if a Directory Exists

if [ -d "myfolder" ]; then
  echo "Directory exists."
else
  echo "Directory does not exist."
fi

6. Safe Scripting Practices

  • Use wildcards cautiously: e.g. rm *.txt deletes all .txt files in a directory.
  • Avoid destructive commands without confirmation: Add prompts or dry runs.
  • Quote variables: Always double-quote variables—"$filename"—to handle spaces.
  • Back up critical data: Before mass operations, make backups.

7. Example Script: Organizing Log Files

Here's a sample script to move old log files into an archive directory:

#!/bin/bash

mkdir -p archive

for file in *.log; do
  if [ -f "$file" ]; then
    mv "$file" archive/
    echo "Moved $file to archive/"
  fi
done

Conclusion

Shell scripting makes file and directory management efficient and automatable. By mastering touch, mkdir, rm, cp, and mv—and incorporating safe scripting practices—you can handle almost any file operation needed for automation or daily tasks.

Happy scripting!