
Part 1: File Input and Output in Bash
1️⃣ Standard Streams
Bash works with three standard streams by default:
stdin (0) → Standard input (keyboard or file input)
stdout (1) → Standard output (screen/terminal)
stderr (2) → Standard error (error messages)
2️⃣ Output Redirection (>
, >>
)
You can redirect command output to a file instead of the screen.
$$
echo “Hello World” > output.txt
$$
$$
echo “New line” >> output.txt
$$
3️⃣ Input Redirection (<
)
Feed a file as input to a command:
$$
sort < names.txt
$$
4️⃣ Redirecting Errors (2>
, 2>>
)
Separate normal output and errors:
$$
ls /nonexistent 2> error.log
$$
Redirect both stdout and stderr together:
$$
command > output.log 2>&1
$$
5️⃣ Here Documents (<<
)
Pass multiple lines of input directly to a command:
$$
cat <<EOF
This is line 1
This is line 2
EOF
$$
6️⃣ Here Strings (<<<
)
Pass a string directly as input:
$$
wc -w <<< “Bash scripting is powerful”
$$
Part 2: Working with Files in Bash
1️⃣ Creating Files
$$
touch file1.txt
$$
$$
2️⃣ Viewing Files
$$
cat file.txt # Show entire content
less file.txt # Scroll through content
head file.txt # First 10 lines
tail file.txt # Last 10 lines
tail -f logfile # Live updates
$$
3️⃣ Copying and Moving Files
$$
cp file1.txt backup.txt # Copy
mv file1.txt newname.txt # Move/Rename
$$
4️⃣ Deleting Files
$$
rm file.txt
$$
⚠️ Warning: Deletion is permanent unless you use trash-cli
or similar tools.
5️⃣ Checking File Types
$$
file myscript.sh
$$
6️⃣ File Tests
Bash provides file test operators for scripts:
$$
[ -f file.txt ] # true if file exists
[ -d dir ] # true if directory exists
[ -r file.txt ] # true if readable
[ -w file.txt ] # true if writable
[ -x script.sh ] # true if executable
$$
Part 3: Working with Directories
1️⃣ Creating Directories
$$
mkdir projects
mkdir -p work/scripts/logs # Creates nested directories
$$
2️⃣ Navigating Directories
$$
cd /home/user
pwd
$$
3️⃣ Listing Directory Contents
$$
ls
ls -l # Detailed view
ls -a # Include hidden files
ls -lh # Human-readable sizes
$$
4️⃣ Removing Directories
$$
rmdir emptydir
rm -r nonemptydir
$$
5️⃣ Copying Directories
$$
cp -r dir1 dir2
$$
6️⃣ Finding Files and Directories
$$
find /home -name “*.txt”
$$
Part 4: Real-World Use Cases
1. Log Rotation
Redirect logs into files daily:
$$
echo “$(date): Script executed” >> script.log
$$
2. Backup Script
Copy important files into a timestamped directory:
$$
backup_dir=“backup_$(date +%F)”
mkdir “$backup_dir”
cp *.txt “$backup_dir”
$$
3. Cleaning Temporary Files
Remove .tmp
files in /tmp
automatically:
$$
find /tmp -name “*.tmp” -delete
$$
4. Archiving
Combine redirection with archiving:
$$
tar -czf logs.tar.gz *.log
$$