# Shell Scripting Extended Cheat Sheet
# 1. Shebang
#!/bin/bash
# 2. Comments
# Single-line comment
: '
Multi-line comment
'
# 3. Variables
NAME="John"
echo "Hello, $NAME"
# 4. User Input
echo "Enter your name: "
read NAME
echo "Hello, $NAME"
# 5. Arithmetic Operations
a=5
b=10
sum=$((a + b))
echo "Sum: $sum"
# 6. Conditional Statements
if [ $a -gt $b ]; then
echo "$a is greater than $b"
else
echo "$a is not greater than $b"
fi
# Nested if statements
if [ $a -gt 0 ]; then
if [ $b -gt 0 ]; then
echo "Both a and b are positive"
fi
fi
# 7. Loops
# For Loop
for i in {1..5}; do
echo "Welcome $i"
done
# While Loop
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
# Until Loop
count=1
until [ $count -gt 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
# 8. Functions
greet() {
echo "Hello, $1"
}
greet "World"
# Function with return value
add() {
local sum=$(( $1 + $2 ))
echo $sum
}
result=$(add 5 3)
echo "Sum: $result"
# 9. File Operations
# Create a file
touch myfile.txt
# Write to a file
echo "Hello, World" > myfile.txt
# Append to a file
echo "This is a new line" >> myfile.txt
# Read from a file
cat myfile.txt
# Check if a file exists
if [ -f myfile.txt ]; then
echo "File exists"
else
echo "File does not exist"
fi
# 10. Basic Commands
# List files
ls
# Change directory
cd /path/to/directory
# Copy files
cp source.txt destination.txt
# Move files
mv source.txt destination.txt
# Remove files
rm myfile.txt
# 11. Error Handling
command_that_fails || { echo "Command failed"; exit 1; }
# 12. Arrays
arr=("apple" "banana" "cherry")
echo ${arr[0]} # apple
echo ${arr[@]} # all elements
# 13. String Manipulation
str="Hello, World"
echo ${str:7:5} # World
echo ${str/World/Shell} # Hello, Shell
# 14. Environment Variables
echo $HOME
echo $PATH
# 15. Sourcing Scripts
# source another_script.sh
# 16. Command Substitution
today=$(date)
echo "Today's date: $today"
# 17. File Permissions
# chmod +x script.sh (make executable)
# chmod 755 script.sh (rwxr-xr-x)
# 18. Exit Status
# echo $? (last command's exit status)
# 19. Logging
log_file="script.log"
echo "Log entry" >> $log_file
# 20. Trap Signals
trap 'echo "Interrupted"; exit' INT
# 21. Debugging
# Use set -x to enable debugging
set -x
# Your code here
set +x
# 22. Case Statements
case $1 in
start)
echo "Starting"
;;
stop)
echo "Stopping"
;;
*)
echo "Usage: $0 {start|stop}"
;;
esac
# 23. Here Documents
cat << EOF
This is a
multi-line
string.
EOF
# 24. Background Jobs
sleep 10 &
wait
# 25. Networking
ping -c 4 google.com
curl http://example.com
# 26. Functions with Arguments
say_hello() {
local name=$1
echo "Hello, $name!"
}
say_hello "Alice"
# 27. Function with Global Variable
counter=0
increment() {
counter=$((counter + 1))
}
increment
echo "Counter: $counter"
# 28. Check Command Success
mkdir new_directory
if [ $? -eq 0 ]; then
echo "Directory created successfully"
else
echo "Failed to create directory"
fi
# 29. Using Expr for Arithmetic
sum=$(expr 3 + 2)
echo "Sum using expr: $sum"
# 30. Handling Arguments
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "All arguments: $@"
# 31. Iterating Over Arguments
for arg in "$@"; do
echo "Argument: $arg"
done
# 32. Select Statement for Menus
PS3="Select an option: "
select opt in "Option 1" "Option 2" "Quit"; do
case $opt in
"Option 1")
echo "You chose Option 1"
;;
"Option 2")
echo "You chose Option 2"
;;
"Quit")
break
;;
*)
echo "Invalid option"
;;
esac
done
# 33. Reading a File Line by Line
while IFS= read -r line; do
echo "Line: $line"
done < myfile.txt
# 34. Processing Command Line Options with getopts
while getopts "a:b:c" opt; do
case $opt in
a)
echo "Option a: $OPTARG"
;;
b)
echo "Option b: $OPTARG"
;;
c)
echo "Option c selected"
;;
*)
echo "Invalid option"
;;
esac
done
# 35. Checking If a Directory Exists
DIR="/path/to/dir"
if [ -d "$DIR" ]; then
echo "Directory exists"
else
echo "Directory does not exist"
fi
# 36. Working with Dates
current_date=$(date +"%Y-%m-%d")
echo "Current date: $current_date"
# 37. Scheduling Tasks with Cron
# Edit the cron jobs
# crontab -e
# Example cron job to run a script every day at 5 AM:
# 0 5 * * * /path/to/script.sh
# 38. Compressing Files
tar -czvf archive.tar.gz /path/to/directory
# 39. Decompressing Files
tar -xzvf archive.tar.gz
# 40. Checking Disk Usage
df -h
# 41. Checking Free Memory
free -h
# 42. Finding Files
find /path/to/search -name "filename"
# 43. Secure Copy (SCP)
scp user@remote:/path/to/remote-file /path/to/local-dir
# 44. Using awk for Text Processing
echo "Hello World" | awk '{print $2}'
# 45. Using sed for Text Substitution
echo "Hello World" | sed 's/World/Shell/'
# 46. Looping Through Files in a Directory
for file in /path/to/directory/*; do
echo "Processing $file"
done
# 47. Working with JSON (requires jq)
# sudo apt-get install jq
json_data='{"name": "John", "age": 30}'
echo $json_data | jq '.name'
# 48. Checking Internet Connectivity
if ping -c 1 google.com &> /dev/null; then
echo "Internet is up"
else
echo "Internet is down"
fi
# 49. Creating Temporary Files
tempfile=$(mktemp)
echo "Temporary file: $tempfile"
# 50. Multi-threading with xargs
# List all files and use xargs to perform actions concurrently
ls | xargs -n1 -P4 -I{} echo "Processing {}"
# End of Extended Cheat Sheet
0 Comments