Bash by Example: Delete File
Bash 5.0+
Removing files and directories using the rm command with various safety options, understanding the permanent nature of rm and lack of trash/recycle bin, using -i for interactive confirmation, implementing -r for recursive directory deletion, applying -f to force deletion, and following best practices to prevent accidental data loss.
Code
#!/bin/bash
# Create dummy files
touch file1.txt file2.txt
mkdir -p mydir
# 1. Remove a single file
rm file1.txt
echo "Removed file1.txt"
# 2. Remove multiple files
touch a.tmp b.tmp
rm a.tmp b.tmp
# 3. Force remove (no error if missing, no prompt)
rm -f non_existent_file.txt
# 4. Interactive remove (prompts for confirmation)
# rm -i file2.txt
# 5. Recursive remove (for directories)
# WARNING: Be very careful with -rf
rm -rf mydir
echo "Removed directory mydir"Explanation
The rm (remove) command is used to delete files and directories. Unlike the Recycle Bin in GUI environments, files deleted with rm are generally not recoverable.
Common flags include:
-f(force): Ignore nonexistent files and arguments, never prompt.-i(interactive): Prompt before every removal. Good for safety.-ror-R(recursive): Remove directories and their contents recursively.
A common idiom is rm -rf to forcefully remove a directory and everything inside it. This is powerful but dangerous; always double-check the path before running it.
Code Breakdown
8
Standard file removal. If the file is write-protected,
rm might prompt for confirmation unless -f is used.16
rm -f is useful in scripts to ensure a clean state without causing the script to fail if the file is already gone.23
rm -rf is required to delete a directory. rm without -r will refuse to remove a directory.
