Cybersecurity Updates & Tools

How To Work With Files And Directories Using Bash Scripts

Introduction

Working with files and directories is one of the most important skills in Bash scripting. Many Linux automation tasks involve creating folders, copying files, moving files, deleting files, checking paths, and organizing data. If you are learning Bash scripting, file and directory handling is a must-know topic.

Bash scripts are commonly used to manage backups, logs, reports, configuration files, scan results, and temporary files. For cybersecurity learners, Bash can help organize security reports, save scan outputs, check log files, and automate file-based tasks.

Create Files Using Bash

You can create an empty file using the touch command.

touch report.txt

Inside a Bash script:

#!/bin/bashtouch security-report.txtecho "File created successfully"

You can also write content into a file using echo:

echo "This is a Bash file example" > report.txt

The > operator creates or overwrites a file.

Create Directories Using Bash

To create a directory, use the mkdir command.

mkdir backups

To create parent directories if they do not exist, use:

mkdir -p backups/logs

Example script:

#!/bin/bashbackup_dir="$HOME/backups"mkdir -p "$backup_dir"echo "Backup directory created at: $backup_dir"

Copy Files Using Bash

To copy a file, use the cp command.

cp file.txt backup-file.txt

Example script:

#!/bin/bashcp report.txt report-backup.txtecho "File copied successfully"

To copy a directory, use:

cp -r old-folder new-folder

The -r option copies directories recursively.

Move Or Rename Files

The mv command is used to move or rename files.

Rename a file:

mv oldname.txt newname.txt

Move a file to another directory:

mv report.txt backups/

Example script:

#!/bin/bashmkdir -p reportsmv security-report.txt reports/echo "Report moved to reports directory"

Delete Files And Directories

To delete a file, use:

rm file.txt

To delete an empty directory:

rmdir foldername

To delete a directory with files inside:

rm -r foldername

Be careful with rm -r because deleted files may not be easy to recover.

Cybersecurity Example: Organize Scan Results

#!/bin/bashtarget="192.168.1.1"scan_dir="$HOME/security-scans"mkdir -p "$scan_dir"echo "Running scan on $target..."nmap "$target" > "$scan_dir/nmap-result.txt"echo "Scan result saved in: $scan_dir"

This script creates a directory and saves an Nmap scan result inside it.

Conclusion

Working with files and directories using Bash scripts is a basic but powerful skill. You can create, copy, move, rename, and delete files automatically. You can also create directories for backups, logs, reports, and scan results.

For beginners, learning file and directory handling in Bash is essential for Linux automation, system administration, backup management, and cybersecurity scripting.