Bash is a powerful shell scripting language that enables automation, text processing, and system administration tasks.
This guide covers basics, intermediate, and advanced techniques with useful gotchas to avoid common pitfalls.
#!/bin/bash # Shebang - Defines the interpreter
echo "Hello, World!" # Print to stdout
name="Bash"
echo "Welcome to $name scripting!"
Gotcha: Always avoid spaces around = in variable assignments.
x = 10 # ❌ Incorrect (spaces are not allowed)
x=10 # ✅ Correct
echo "Enter your name:"
read username
echo "Hello, $username!"
x=10
if [[ $x -gt 5 ]]; then
echo "x is greater than 5"
else
echo "x is 5 or less"
fi
For Loop:
for i in {1..5}; do
echo "Iteration $i"
done
While Loop:
count=1
while [[ $count -le 5 ]]; do
echo "Count: $count"
((count++)) # Increment count
done
mkdir mydir # Create directory
touch file.txt # Create file
rm file.txt # Remove file
ls -lah # List files with details
if [[ -f "myfile.txt" ]]; then
echo "File exists"
else
echo "File does not exist"
fi
greet() {
echo "Hello, $1!"
}
greet "Alice" # Output: Hello, Alice!
fruits=("Apple" "Banana" "Cherry")
echo "${fruits[0]}" # Access first element
echo "${fruits[@]}" # Access all elements
# Loop through array
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done
Incorrect:
myarr=("one word" "two words")
echo $myarr # ❌ Expands to "one word two words"
Correct:
echo "${myarr[@]}" # ✅ Expands correctly
declare -A mydict
mydict[username]="admin"
mydict[password]="secret"
echo "Username: ${mydict[username]}"
echo "All keys: ${!mydict[@]}"
diff <(ls dir1) <(ls dir2) # Compare directory listings
DATE=$(date +"%Y-%m-%d")
echo "Today's date is $DATE"
VAR=$(echo "hello world")
echo $VAR # ❌ Collapses spaces: "hello world"
echo "$VAR" # ✅ Preserves spaces: "hello world"
set -euxo pipefail for Robust Scriptsset -euxo pipefail # Enable strict error handling
cmd1 & cmd2 & wait # Run cmd1 and cmd2 in parallel, then wait
while IFS= read -r line; do
echo "Line: $line"
done < myfile.txt
bash -x myscript.sh # Run script with debugging enabled
ls | grep "pattern" > output.txt # Redirect output to file
set -euxo pipefail to avoid silent failures.[[ ... ]] over [ ... ] for conditionals."$var") to prevent word splitting issues.🚀 Happy Scripting! 🐧