Bash Scripting Commands Cheatsheet
Table of Contents
- Basic Commands & Navigation
- File Operations
- Text Processing
- Variables & Data Types
- Conditional Statements
- Loops
- Functions
- Arrays
- String Manipulation
- Process Management
- Networking
- File Permissions
- Archive & Compression
- Search & Find
- Input/Output Redirection
- Here Documents
- Command Substitution
- Regular Expressions
- Debugging
- Error Handling
- Script Optimization
- Advanced Bash Features
- Bash Best Practices
- Interview Scenarios
Basic Commands & Navigation
1. Print Current Directory
pwd2. Change Directory
cd /path/to/directory
cd ~ # Home directory
cd .. # Parent directory
cd - # Previous directory3. List Files
ls -la # Detailed list with hidden files
ls -lh # Human-readable sizes
ls -lrt # Sort by modification time (oldest first)
ls -S # Sort by file size4. Echo Command
echo "Hello World"
echo -n "No newline"
echo -e "Line1\nLine2" # Enable escape sequences5. Command History
history # Show command history
!! # Execute last command
!n # Execute command number n
!string # Execute last command starting with 'string'
history | grep keywordFile Operations
6. Create Files
touch file.txt
touch file{1..10}.txt # Create multiple files7. Create Directories
mkdir directory
mkdir -p parent/child/grandchild # Create nested directories8. Copy Files
cp source.txt destination.txt
cp -r source_dir/ dest_dir/ # Recursive copy
cp -p file.txt backup.txt # Preserve attributes
cp -v file.txt dest/ # Verbose output9. Move/Rename Files
mv oldname.txt newname.txt
mv file.txt /new/location/
mv *.txt /destination/10. Remove Files
rm file.txt
rm -f file.txt # Force removal
rm -r directory/ # Recursive removal
rm -rf directory/ # Force recursive removal
rm -i file.txt # Interactive (confirm before delete)11. View File Content
cat file.txt # Display entire file
head -n 10 file.txt # First 10 lines
tail -n 10 file.txt # Last 10 lines
tail -f log.txt # Follow file updates
less file.txt # Page through file
more file.txt # Page through file (basic)12. File Information
file document.pdf # Determine file type
stat file.txt # Detailed file statistics
wc -l file.txt # Count lines
wc -w file.txt # Count words
wc -c file.txt # Count bytesText Processing
13. grep - Search Text
grep "pattern" file.txt
grep -i "pattern" file.txt # Case-insensitive
grep -r "pattern" directory/ # Recursive search
grep -n "pattern" file.txt # Show line numbers
grep -v "pattern" file.txt # Invert match (exclude)
grep -E "pattern1|pattern2" file.txt # Extended regex (OR)
grep -A 5 "pattern" file.txt # Show 5 lines after match
grep -B 5 "pattern" file.txt # Show 5 lines before match
grep -C 5 "pattern" file.txt # Show 5 lines before and after14. sed - Stream Editor
sed 's/old/new/' file.txt # Replace first occurrence
sed 's/old/new/g' file.txt # Replace all occurrences
sed -i 's/old/new/g' file.txt # In-place editing
sed -n '10,20p' file.txt # Print lines 10-20
sed '/pattern/d' file.txt # Delete lines matching pattern
sed '5d' file.txt # Delete line 5
sed 's/^/prefix/' file.txt # Add prefix to each line15. awk - Text Processing
awk '{print $1}' file.txt # Print first column
awk '{print $1, $3}' file.txt # Print columns 1 and 3
awk -F: '{print $1}' /etc/passwd # Custom delimiter
awk 'NR==10' file.txt # Print line 10
awk 'NR>=10 && NR<=20' file.txt # Print lines 10-20
awk '{sum+=$1} END {print sum}' # Sum column 1
awk 'length($0) > 80' file.txt # Lines longer than 80 chars16. cut - Extract Columns
cut -d',' -f1 file.csv # Extract first field (CSV)
cut -c1-10 file.txt # Extract characters 1-10
cut -f2,4 file.tsv # Extract fields 2 and 417. sort - Sort Lines
sort file.txt # Alphabetical sort
sort -r file.txt # Reverse sort
sort -n file.txt # Numeric sort
sort -u file.txt # Unique sorted lines
sort -k2 file.txt # Sort by column 2
sort -t',' -k3 file.csv # CSV sort by column 318. uniq - Remove Duplicates
uniq file.txt # Remove adjacent duplicates
uniq -c file.txt # Count occurrences
uniq -d file.txt # Show only duplicates
uniq -u file.txt # Show only unique lines19. tr - Translate Characters
tr 'a-z' 'A-Z' < file.txt # Lowercase to uppercase
tr -d '[:digit:]' < file.txt # Delete digits
tr -s ' ' < file.txt # Squeeze multiple spaces
echo "hello" | tr 'a-z' 'A-Z' # HELLO20. paste - Merge Lines
paste file1.txt file2.txt # Merge files side by side
paste -d',' file1.txt file2.txt # CSV merge
paste -s file.txt # Serialize (all lines in one)Variables & Data Types
21. Variable Assignment
name="John"
age=30
readonly PI=3.14 # Read-only variable22. Variable Usage
echo $name
echo ${name} # Recommended
echo "Hello $name"23. Command Output in Variable
current_date=$(date)
files_count=$(ls | wc -l)24. Environment Variables
export PATH=$PATH:/new/path
export DATABASE_URL="postgres://..."
echo $HOME
echo $USER
echo $SHELL
printenv # Show all env vars25. Special Variables
$0 # Script name
$1-$9 # Positional parameters
$# # Number of parameters
$@ # All parameters as separate words
$* # All parameters as single word
$? # Exit status of last command
$$ # Current process ID
$! # PID of last background job26. Default Values
${var:-default} # Use default if var is unset
${var:=default} # Assign default if var is unset
${var:+alternative} # Use alternative if var is set
${var:?error_msg} # Exit with error if var is unsetConditional Statements
27. If Statement
if [ condition ]; then
echo "True"
fi28. If-Else
if [ $age -gt 18 ]; then
echo "Adult"
else
echo "Minor"
fi29. If-Elif-Else
if [ $score -ge 90 ]; then
echo "A"
elif [ $score -ge 80 ]; then
echo "B"
else
echo "C"
fi30. File Test Operators
[ -f file.txt ] # File exists and is regular file
[ -d directory ] # Directory exists
[ -e path ] # Path exists
[ -r file.txt ] # File is readable
[ -w file.txt ] # File is writable
[ -x script.sh ] # File is executable
[ -s file.txt ] # File is not empty
[ -L link ] # Is symbolic link31. String Comparison
[ "$str1" = "$str2" ] # Strings are equal
[ "$str1" != "$str2" ] # Strings are not equal
[ -z "$str" ] # String is empty
[ -n "$str" ] # String is not empty32. Numeric Comparison
[ $a -eq $b ] # Equal
[ $a -ne $b ] # Not equal
[ $a -gt $b ] # Greater than
[ $a -ge $b ] # Greater than or equal
[ $a -lt $b ] # Less than
[ $a -le $b ] # Less than or equal33. Logical Operators
[ condition1 ] && [ condition2 ] # AND
[ condition1 ] || [ condition2 ] # OR
[ ! condition ] # NOT34. Case Statement
case $variable in
pattern1)
echo "Pattern 1"
;;
pattern2)
echo "Pattern 2"
;;
*)
echo "Default"
;;
esacLoops
35. For Loop - List
for item in apple banana cherry; do
echo $item
done36. For Loop - Range
for i in {1..10}; do
echo $i
done
for i in {0..100..10}; do # Step by 10
echo $i
done37. For Loop - C-Style
for ((i=0; i<10; i++)); do
echo $i
done38. For Loop - Files
for file in *.txt; do
echo "Processing $file"
done39. While Loop
counter=0
while [ $counter -lt 10 ]; do
echo $counter
((counter++))
done40. Until Loop
counter=0
until [ $counter -ge 10 ]; do
echo $counter
((counter++))
done41. Read File Line by Line
while IFS= read -r line; do
echo "$line"
done < file.txt42. Loop Control
for i in {1..10}; do
if [ $i -eq 5 ]; then
continue # Skip iteration
fi
if [ $i -eq 8 ]; then
break # Exit loop
fi
echo $i
doneFunctions
43. Function Definition
function greet() {
echo "Hello $1"
}
# Alternative syntax
greet() {
echo "Hello $1"
}44. Function with Return Value
add() {
local result=$(($1 + $2))
echo $result
}
sum=$(add 5 3)
echo $sum # 845. Function with Return Code
is_valid() {
if [ $1 -gt 0 ]; then
return 0 # Success
else
return 1 # Failure
fi
}
if is_valid 5; then
echo "Valid"
fi46. Local Variables
my_function() {
local local_var="I'm local"
global_var="I'm global"
}47. Function with Multiple Returns
get_user_info() {
echo "John"
echo "30"
echo "john@example.com"
}
IFS=$'\n' read -r -d '' name age email < <(get_user_info)Arrays
48. Array Declaration
fruits=("apple" "banana" "cherry")
numbers=(1 2 3 4 5)
declare -a array_name49. Access Array Elements
echo ${fruits[0]} # First element
echo ${fruits[@]} # All elements
echo ${fruits[*]} # All elements as single word
echo ${#fruits[@]} # Array length50. Add to Array
fruits+=("orange") # Append element
fruits[3]="grape" # Set by index51. Iterate Over Array
for fruit in "${fruits[@]}"; do
echo $fruit
done
# With index
for i in "${!fruits[@]}"; do
echo "Index $i: ${fruits[$i]}"
done52. Array Slicing
echo ${fruits[@]:1:2} # Elements from index 1, length 2
echo ${fruits[@]:2} # Elements from index 2 to end53. Associative Arrays (Hash/Dictionary)
declare -A user
user[name]="John"
user[age]=30
user[email]="john@example.com"
echo ${user[name]}
echo ${user[@]} # All values
echo ${!user[@]} # All keysString Manipulation
54. String Length
str="Hello World"
echo ${#str} # 1155. Substring Extraction
echo ${str:0:5} # "Hello" - from index 0, length 5
echo ${str:6} # "World" - from index 6 to end
echo ${str: -5} # "World" - last 5 characters56. String Replace
echo ${str/World/Universe} # Replace first occurrence
echo ${str//o/O} # Replace all occurrences57. String Remove Pattern
filename="document.pdf"
echo ${filename%.pdf} # Remove shortest match from end: "document"
echo ${filename%.*} # "document"
echo ${filename#*.} # Remove shortest match from start: "pdf"58. Upper/Lowercase
str="Hello World"
echo ${str^^} # HELLO WORLD (uppercase)
echo ${str,,} # hello world (lowercase)
echo ${str^} # Hello World (capitalize first char)59. String Concatenation
first="Hello"
last="World"
full="$first $last"
full="${first} ${last}"Process Management
60. Background Jobs
command & # Run in background
jobs # List background jobs
fg %1 # Bring job 1 to foreground
bg %1 # Resume job 1 in background61. Process Information
ps aux # All processes
ps aux | grep process_name
pgrep process_name # Find process ID by name
pidof process_name62. Kill Processes
kill PID # Terminate process
kill -9 PID # Force kill
killall process_name # Kill all instances
pkill pattern # Kill by pattern63. Process Priority
nice -n 10 command # Run with lower priority
renice -n 5 -p PID # Change priority64. Timeout Command
timeout 10s command # Kill after 10 seconds
timeout 5m long_task.sh # Kill after 5 minutes65. Wait for Process
command &
wait $! # Wait for last background job
wait # Wait for all background jobsNetworking
66. Curl - HTTP Requests
curl https://api.example.com
curl -X POST https://api.example.com/data
curl -H "Content-Type: application/json" -d '{"key":"value"}' URL
curl -o output.html https://example.com
curl -I https://example.com # Headers only
curl -L https://example.com # Follow redirects67. Wget - Download Files
wget https://example.com/file.zip
wget -O newname.zip https://example.com/file.zip
wget -c https://example.com/file.zip # Resume download
wget -r https://example.com # Recursive download68. Network Information
ifconfig # Network interfaces (deprecated)
ip addr # IP addresses
ip route # Routing table
netstat -tuln # Listening ports
ss -tuln # Socket statistics (modern)69. DNS Lookup
nslookup example.com
dig example.com
host example.com70. Ping & Trace
ping -c 4 example.com # Send 4 packets
traceroute example.com
tracepath example.com71. Port Scanning
nc -zv example.com 80 # Check if port 80 is open
nmap -p 80,443 example.com
telnet example.com 80File Permissions
72. View Permissions
ls -l file.txt
stat file.txt73. Change Permissions (chmod)
chmod 755 file.sh # rwxr-xr-x
chmod u+x file.sh # Add execute for user
chmod g-w file.txt # Remove write for group
chmod o=r file.txt # Set others to read-only
chmod -R 755 directory/ # Recursive74. Change Owner (chown)
chown user file.txt
chown user:group file.txt
chown -R user:group directory/75. Change Group (chgrp)
chgrp group file.txt
chgrp -R group directory/76. Special Permissions
chmod u+s file # Set SUID
chmod g+s directory # Set SGID
chmod +t directory # Set sticky bit77. Default Permissions (umask)
umask # View current umask
umask 022 # Set umaskArchive & Compression
78. tar - Archive
tar -cvf archive.tar files/ # Create archive
tar -xvf archive.tar # Extract archive
tar -tvf archive.tar # List contents
tar -czvf archive.tar.gz files/ # Create compressed (gzip)
tar -xzvf archive.tar.gz # Extract compressed
tar -cjvf archive.tar.bz2 files/ # Create compressed (bzip2)
tar -C /destination -xvf archive.tar # Extract to directory79. gzip - Compress
gzip file.txt # Compress (creates file.txt.gz)
gzip -d file.txt.gz # Decompress
gunzip file.txt.gz # Decompress
gzip -k file.txt # Keep original file80. zip/unzip
zip archive.zip file1.txt file2.txt
zip -r archive.zip directory/
unzip archive.zip
unzip -l archive.zip # List contents
unzip archive.zip -d /path/ # Extract to directory81. bzip2
bzip2 file.txt
bunzip2 file.txt.bz2Search & Find
82. find - Search Files
find /path -name "*.txt"
find . -type f -name "file.txt" # Files only
find . -type d -name "dirname" # Directories only
find . -mtime -7 # Modified in last 7 days
find . -size +100M # Larger than 100MB
find . -user username # Owned by user
find . -perm 755 # Specific permissions83. find with Actions
find . -name "*.log" -delete # Delete files
find . -name "*.txt" -exec cat {} \; # Execute command
find . -type f -exec chmod 644 {} \; # Change permissions
find . -name "*.bak" -exec rm {} \; # Remove backups84. locate - Fast Search
locate filename
updatedb # Update locate database (requires sudo)85. which - Find Command Location
which python
which -a python # All occurrences in PATH86. whereis - Locate Binary/Man Page
whereis python
whereis -b python # Binary only
whereis -m python # Man page onlyInput/Output Redirection
87. Output Redirection
command > file.txt # Overwrite file
command >> file.txt # Append to file
command 2> error.log # Redirect stderr
command &> output.log # Redirect stdout and stderr
command > /dev/null # Discard output88. Input Redirection
command < input.txt
command << EOF # Here document
line 1
line 2
EOF89. Pipelines
command1 | command2
ls -l | grep ".txt"
ps aux | grep nginx | awk '{print $2}'90. tee - Output to File and stdout
command | tee output.txt
command | tee -a output.txt # Append
command 2>&1 | tee output.log # Include stderrHere Documents
91. Basic Here Document
cat << EOF > file.txt
Line 1
Line 2
Variable: $VAR
EOF92. Here Document without Variable Expansion
cat << 'EOF' > file.txt
Line 1
Variable will not expand: $VAR
EOF93. Here Strings
grep "pattern" <<< "$string"
base64 <<< "encode this"Command Substitution
94. Command Substitution (Modern)
result=$(command)
current_date=$(date +%Y-%m-%d)
file_count=$(ls | wc -l)95. Command Substitution (Legacy)
result=`command` # Backticks (deprecated)96. Arithmetic Expansion
echo $((5 + 3)) # 8
((counter++))
result=$((10 * 20))Regular Expressions
97. grep with Regex
grep "^start" file.txt # Lines starting with
grep "end$" file.txt # Lines ending with
grep "[0-9]" file.txt # Contains digit
grep "^[A-Z]" file.txt # Starts with uppercase
grep -E "color|colour" file.txt # Alternation98. sed with Regex
sed 's/[0-9]\{3\}-[0-9]\{4\}/REDACTED/g' # Phone numbers
sed 's/^[[:space:]]*//' file.txt # Remove leading whitespace99. Pattern Matching
[[ $string =~ ^[0-9]+$ ]] && echo "Number"
[[ $email =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]Debugging
100. Debug Mode
bash -x script.sh # Execute with trace
set -x # Enable debugging
set +x # Disable debugging101. Verbose Mode
bash -v script.sh
set -v # Enable verbose
set +v # Disable verbose102. Syntax Check
bash -n script.sh # Check syntax without execution
shellcheck script.sh # Static analysis tool103. Exit on Error
set -e # Exit on any error
set -u # Exit on undefined variable
set -o pipefail # Exit on pipe failure
set -euo pipefail # Combine all safety options104. Trap Errors
trap 'echo "Error on line $LINENO"' ERR
trap 'cleanup' EXIT # Run cleanup on exitError Handling
105. Check Command Success
if command; then
echo "Success"
else
echo "Failed"
fi106. Exit Status
command
if [ $? -eq 0 ]; then
echo "Success"
fi107. Short-circuit Evaluation
command && echo "Success" || echo "Failed"
mkdir /tmp/test && cd /tmp/test || exit 1108. Custom Error Messages
command || { echo "Error: command failed" >&2; exit 1; }Script Optimization
109. Parallel Execution
command1 &
command2 &
wait # Wait for all background jobs110. xargs - Parallel Processing
cat files.txt | xargs -P 4 -I {} process {}
find . -name "*.txt" | xargs -P 8 -I {} gzip {}111. Performance Measurement
time command
time { command1; command2; }112. Efficient Loops
# Avoid: for i in $(cat file)
# Use: while read line
while IFS= read -r line; do
echo "$line"
done < file.txtAdvanced Bash Features
113. Brace Expansion
echo {A..Z} # A B C ... Z
echo {1..10} # 1 2 3 ... 10
mkdir -p project/{src,test,docs}
cp file.txt{,.bak} # file.txt file.txt.bak114. Parameter Expansion
${var#pattern} # Remove shortest match from start
${var##pattern} # Remove longest match from start
${var%pattern} # Remove shortest match from end
${var%%pattern} # Remove longest match from end
${var/pattern/replacement} # Replace first occurrence
${var//pattern/replacement} # Replace all occurrences115. Process Substitution
diff <(command1) <(command2)
while read line; do
echo $line
done < <(command)116. Named Pipes (FIFO)
mkfifo mypipe
command1 > mypipe &
command2 < mypipe117. Coprocesses
coproc my_proc { command; }
echo "data" >&${my_proc[1]}
read result <&${my_proc[0]}118. Subshells
(cd /tmp && command) # Changes directory in subshell only
{ command1; command2; } # Execute in current shell119. Signal Handling
trap 'cleanup' INT TERM EXIT
trap 'echo "Received SIGUSR1"' SIGUSR1120. Random Numbers
echo $RANDOM # Random number 0-32767
echo $(($RANDOM % 100)) # Random number 0-99Advanced Commands
121. xargs - Build Command Lines
echo "file1 file2" | xargs rm
find . -name "*.txt" | xargs grep "pattern"
cat urls.txt | xargs -n 1 curl122. jq - JSON Processing
echo '{"name":"John","age":30}' | jq '.name'
curl api.example.com | jq '.data[] | {id, name}'
jq -r '.items[].name' data.json123. Column Formatting
column -t file.txt # Align columns
mount | column -t124. Watch Command
watch -n 5 command # Run every 5 seconds
watch -d command # Highlight differences125. Screen/Tmux
screen # New session
screen -r # Reattach
tmux new -s session_name
tmux attach -t session_name126. rsync - Sync Files
rsync -av source/ destination/
rsync -avz --progress source/ user@host:/path/
rsync -av --delete source/ destination/ # Mirror
rsync -av --exclude='*.log' source/ dest/127. ln - Create Links
ln -s target link_name # Symbolic link
ln target link_name # Hard link128. Date/Time Operations
date +%Y-%m-%d # 2026-02-15
date +%s # Unix timestamp
date -d "yesterday"
date -d "next monday"
date -d "@1234567890" # From timestamp129. Math Operations
echo "scale=2; 10/3" | bc # 3.33
echo "sqrt(16)" | bc # 4
expr 5 + 3 # 8130. Base64 Encoding
echo "text" | base64 # Encode
echo "dGV4dAo=" | base64 -d # DecodeNetworking Advanced
131. SSH Operations
ssh user@host
ssh user@host "command" # Remote command
ssh -i key.pem user@host
ssh -L 8080:localhost:80 user@host # Port forwarding
scp file.txt user@host:/path/132. Network Testing
nc -l 8080 # Listen on port
echo "test" | nc host 8080 # Send data
curl -w "@curl-format.txt" https://example.comFile System Operations
133. Disk Usage
df -h # Disk space
du -sh directory/ # Directory size
du -h --max-depth=1 # First level subdirectories134. inode Information
df -i # Inode usage
ls -i file.txt # File inode number135. Mount Operations
mount # List mounts
mount /dev/sdb1 /mnt # Mount device
umount /mnt # UnmountSecurity
136. Checksums
md5sum file.txt
sha256sum file.txt
sha512sum file.txt
md5sum -c checksums.txt # Verify137. File Encryption
openssl enc -aes-256-cbc -in file.txt -out file.enc
openssl enc -aes-256-cbc -d -in file.enc -out file.txt138. Password Generation
openssl rand -base64 32
head /dev/urandom | tr -dc A-Za-z0-9 | head -c 16System Information
139. System Info
uname -a # System information
hostname # Hostname
uptime # System uptime
whoami # Current user
id # User and group IDs140. Resource Usage
top # Process monitor
htop # Enhanced top
free -h # Memory usage
vmstat # Virtual memory stats
iostat # CPU and I/O stats141. Users & Groups
w # Who is logged in
who # Show logged users
last # Last logins
groups username # User's groups
id username # User detailsPackage Management
142. APT (Debian/Ubuntu)
apt update
apt upgrade
apt install package_name
apt remove package_name
apt search keyword143. YUM/DNF (RedHat/CentOS)
yum update
yum install package_name
yum remove package_name
dnf install package_name144. Snap
snap install package_name
snap list
snap remove package_nameLogging
145. System Logs
tail -f /var/log/syslog
journalctl -f # Follow systemd logs
journalctl -u service_name # Service logs
journalctl --since "1 hour ago"146. Logger Command
logger "Log message"
logger -p user.error "Error message"Cron Jobs
147. Crontab Operations
crontab -e # Edit crontab
crontab -l # List cron jobs
crontab -r # Remove crontab
# Cron syntax: minute hour day month weekday command
# 0 2 * * * /path/to/script.sh # Daily at 2 AM
# */5 * * * * command # Every 5 minutes
# 0 0 * * 0 command # Weekly on SundayEnvironment Setup
148. Shell Configuration
source ~/.bashrc # Reload configuration
alias ll='ls -la' # Create alias
unalias ll # Remove alias149. Path Management
export PATH=$PATH:/new/path
echo $PATH | tr ':' '\n' # List PATH directories150. Shell Options
set -o noclobber # Prevent file overwrite with >
set +o noclobber # Allow file overwrite
shopt -s dotglob # Include hidden files in *Bash Best Practices
151. Script Header
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
# Script: name.sh
# Description: What it does
# Author: Your Name
# Date: 2026-02-15152. Input Validation
if [ $# -lt 1 ]; then
echo "Usage: $0 <argument>" >&2
exit 1
fi153. Use Functions
main() {
# Main logic here
}
# Call main function
main "$@"154. Quote Variables
# Good
echo "$var"
cp "$source" "$destination"
# Bad (can break with spaces)
echo $var
cp $source $destination155. Use [[ ]] over [ ]
# Modern (supports &&, ||, regex)
if [[ $var =~ ^[0-9]+$ ]]; then
echo "Number"
fi
# Legacy
if [ "$var" = "value" ]; then
echo "Match"
fiCommon Patterns
156. Configuration File Parsing
while IFS='=' read -r key value; do
[[ $key =~ ^#.*$ ]] && continue # Skip comments
declare "$key=$value"
done < config.ini157. Menu System
PS3="Select option: "
options=("Option 1" "Option 2" "Quit")
select opt in "${options[@]}"; do
case $opt in
"Option 1") echo "Selected 1"; break;;
"Option 2") echo "Selected 2"; break;;
"Quit") break;;
*) echo "Invalid option";;
esac
done158. Progress Bar
for i in {1..100}; do
echo -ne "\rProgress: $i%"
sleep 0.1
done
echo159. Lock File Pattern
LOCKFILE=/var/lock/script.lock
if [ -e "$LOCKFILE" ]; then
echo "Script already running"
exit 1
fi
trap "rm -f $LOCKFILE" EXIT
touch $LOCKFILE160. Argument Parsing
while getopts "f:v" opt; do
case $opt in
f) file=$OPTARG;;
v) verbose=1;;
*) echo "Usage: $0 [-f file] [-v]" >&2; exit 1;;
esac
done
shift $((OPTIND-1))Interview Scenarios
Scenario 1: Find and Delete Old Log Files
Question: Delete log files older than 30 days in /var/log
find /var/log -name "*.log" -mtime +30 -delete
# Or with confirmation
find /var/log -name "*.log" -mtime +30 -exec rm -i {} \;
# Or move to archive
find /var/log -name "*.log" -mtime +30 -exec mv {} /archive/ \;Scenario 2: Monitor Disk Space and Alert
Question: Script that sends alert when disk usage exceeds 80%
#!/bin/bash
threshold=80
usage=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
if [ $usage -gt $threshold ]; then
echo "Disk usage is ${usage}% - exceeds threshold!" | \
mail -s "Disk Alert" admin@example.com
fiScenario 3: Bulk File Renaming
Question: Rename all .txt files to .backup
for file in *.txt; do
mv "$file" "${file%.txt}.backup"
done
# Or using rename command
rename 's/\.txt$/.backup/' *.txtScenario 4: Process CPU Usage
Question: Find top 10 CPU-consuming processes
ps aux --sort=-%cpu | head -11
# Or
top -bn1 | head -n 20Scenario 5: Extract and Count
Question: Count unique IP addresses in access log
awk '{print $1}' access.log | sort | uniq -c | sort -rn
# Or with cut
cut -d' ' -f1 access.log | sort | uniq -c | sort -rnScenario 6: Backup Script
Question: Create automated backup with timestamp
#!/bin/bash
backup_dir="/backup"
source_dir="/data"
timestamp=$(date +%Y%m%d_%H%M%S)
backup_file="${backup_dir}/backup_${timestamp}.tar.gz"
tar -czf "$backup_file" "$source_dir"
# Keep only last 7 backups
ls -t ${backup_dir}/backup_*.tar.gz | tail -n +8 | xargs rm -fScenario 7: Health Check Script
Question: Check if service is running and restart if down
#!/bin/bash
service_name="nginx"
if ! systemctl is-active --quiet $service_name; then
echo "Service $service_name is down, restarting..."
systemctl restart $service_name
sleep 5
if systemctl is-active --quiet $service_name; then
echo "Service restarted successfully"
else
echo "Failed to restart service" | \
mail -s "Service Alert" admin@example.com
fi
fiScenario 8: Log Rotation
Question: Implement simple log rotation
#!/bin/bash
logfile="/var/log/app.log"
max_size=104857600 # 100MB in bytes
if [ -f "$logfile" ]; then
size=$(stat -f%z "$logfile" 2>/dev/null || stat -c%s "$logfile")
if [ $size -gt $max_size ]; then
timestamp=$(date +%Y%m%d_%H%M%S)
mv "$logfile" "${logfile}.${timestamp}"
gzip "${logfile}.${timestamp}"
touch "$logfile"
fi
fiScenario 9: User Activity Report
Question: Generate report of user logins
#!/bin/bash
echo "User Login Report - $(date)"
echo "================================"
last -F | awk '{print $1}' | sort | uniq -c | sort -rn
echo "================================"
echo "Currently logged in:"
whoScenario 10: Deployment Script
Question: Deploy application with rollback capability
#!/bin/bash
set -euo pipefail
app_dir="/opt/myapp"
backup_dir="/opt/backup"
timestamp=$(date +%Y%m%d_%H%M%S)
# Backup current version
cp -r "$app_dir" "${backup_dir}/app_${timestamp}"
# Deploy new version
trap 'echo "Deployment failed, rolling back..."; \
rm -rf "$app_dir"; \
cp -r "${backup_dir}/app_${timestamp}" "$app_dir"' ERR
git pull origin main
npm install --production
npm run build
systemctl restart myapp
echo "Deployment successful"
# Cleanup old backups (keep last 5)
ls -t ${backup_dir}/app_* | tail -n +6 | xargs rm -rfKey Interview Topics
1. Error Handling Best Practices
- Always use
set -euo pipefail - Check command exit codes
- Use trap for cleanup
- Validate input parameters
- Quote all variables
2. Performance Optimization
- Avoid unnecessary commands in loops
- Use built-in Bash features instead of external commands
- Parallel processing with & and wait
- Use while read instead of for with command substitution
3. Security Considerations
- Never store passwords in scripts
- Use environment variables for sensitive data
- Validate and sanitize user input
- Use absolute paths
- Set proper file permissions
4. Common Pitfalls
- Word splitting (not quoting variables)
- Parsing ls output (use find with -print0)
- Using $(cat file) instead of while read
- Not handling spaces in filenames
- Using == instead of = in [ ] tests
5. Script Portability
- Use #!/bin/bash or #!/usr/bin/env bash
- Avoid bashisms if targeting /bin/sh
- Check command availability before use
- Handle different OS variations
Quick Reference
File Test Operators
-e exists
-f regular file
-d directory
-L symbolic link
-r readable
-w writable
-x executable
-s not empty
-nt newer than
-ot older thanString Operators
= equal
!= not equal
-z empty
-n not empty
< less than (in [[]])
> greater than (in [[]])Numeric Operators
-eq equal
-ne not equal
-lt less than
-le less than or equal
-gt greater than
-ge greater than or equalSpecial Parameters
$0 Script name
$1-$9 Arguments
$# Argument count
$@ All arguments (separate)
$* All arguments (single)
$? Exit status
$$ Process ID
$! Last background PIDLast updated on