Getting Started
5 snippetsBasic shell scripting fundamentals
Hello World
#!/bin/bash
echo "Hello, World!" Shebang Variants
#!/bin/bash # Bash
#!/bin/sh # POSIX shell
#!/usr/bin/env bash # Portable Comments
# Single line comment
: '
Multi-line comment
using colon operator
' Make Executable
chmod +x script.sh
./script.sh Run Without Execute Permission
bash script.sh
sh script.sh Variables
6 snippetsVariable declaration and usage
Variable Assignment
name="John" # No spaces around =
count=42
path="/usr/local/bin" Variable Usage
echo $name # Basic usage
echo "${name}" # Explicit braces
echo "Hello, $name" # In strings Command Substitution
today=$(date +%Y-%m-%d)
files=$(ls -l)
count=$(wc -l < file.txt) Read User Input
read -p "Enter name: " username
read -sp "Password: " password # Silent
read -t 5 -p "Quick: " answer # Timeout Environment Variables
export PATH="/usr/local/bin:$PATH"
export DB_HOST="localhost"
env | grep PATH # View all Special Variables
$0 # Script name
$1, $2 # Arguments
$# # Argument count
$@ # All arguments
$? # Last exit status
$$ # Process ID Operators & Comparisons
5 snippetsArithmetic and test operators
Arithmetic
result=$((5 + 3))
count=$((count + 1))
value=$((10 * 2 - 5)) String Comparison
if [ "$str1" = "$str2" ]; then
echo "Equal"
fi
if [ "$str1" != "$str2" ]; then
echo "Not equal"
fi Integer Comparison
if [ $a -eq $b ]; then echo "Equal"; fi
if [ $a -ne $b ]; then echo "Not equal"; fi
if [ $a -gt $b ]; then echo "Greater"; fi
if [ $a -lt $b ]; then echo "Less"; fi File Tests
[ -f file.txt ] # File exists
[ -d /path ] # Directory exists
[ -r file ] # Readable
[ -w file ] # Writable
[ -x file ] # Executable Logical Operators
if [ $a -gt 0 ] && [ $b -gt 0 ]; then
echo "Both positive"
fi
if [ $a -gt 0 ] || [ $b -gt 0 ]; then
echo "At least one positive"
fi Tired of looking up syntax?
DocuWriter.ai generates documentation and explains code using AI.
Control Flow
5 snippetsConditional statements
If Statement
if [ $age -ge 18 ]; then
echo "Adult"
fi If-Else
if [ $score -ge 60 ]; then
echo "Pass"
else
echo "Fail"
fi If-Elif-Else
if [ $grade -ge 90 ]; then
echo "A"
elif [ $grade -ge 80 ]; then
echo "B"
else
echo "C"
fi Case Statement
case $fruit in
apple)
echo "Red"
;;
banana)
echo "Yellow"
;;
*)
echo "Unknown"
;;
esac Test Syntax [[ ]]
if [[ $name == "John" ]]; then
echo "Hello John"
fi
if [[ $str =~ ^[0-9]+$ ]]; then
echo "Number"
fi Loops
7 snippetsIteration constructs
For Loop (List)
for item in apple banana cherry; do
echo $item
done For Loop (Range)
for i in {1..10}; do
echo "Number: $i"
done For Loop (C-style)
for ((i=0; i<10; i++)); do
echo $i
done While Loop
count=0
while [ $count -lt 5 ]; do
echo $count
count=$((count + 1))
done Until Loop
count=0
until [ $count -ge 5 ]; do
echo $count
count=$((count + 1))
done Loop Over Files
for file in *.txt; do
echo "Processing: $file"
wc -l "$file"
done Read Lines from File
while IFS= read -r line; do
echo "Line: $line"
done < file.txt Functions
4 snippetsReusable code blocks
Function Definition
greet() {
echo "Hello, $1"
}
greet "World" Function with Return
add() {
local sum=$(($1 + $2))
echo $sum
}
result=$(add 5 3)
echo "Result: $result" Function with Status
check_file() {
if [ -f "$1" ]; then
return 0 # Success
else
return 1 # Failure
fi
}
if check_file "test.txt"; then
echo "File exists"
fi Local Variables
calculate() {
local x=10
local y=20
echo $((x + y))
} Arrays
6 snippetsWorking with arrays
Array Declaration
fruits=("apple" "banana" "cherry")
numbers=(1 2 3 4 5) Access Elements
echo ${fruits[0]} # First element
echo ${fruits[2]} # Third element
echo ${fruits[-1]} # Last element Array Length
echo ${#fruits[@]} # Number of elements
echo ${#fruits[0]} # Length of first element Loop Through Array
for fruit in "${fruits[@]}"; do
echo $fruit
done Add/Remove Elements
fruits+=("orange") # Append
unset fruits[1] # Remove element Array Slicing
echo ${fruits[@]:1:2} # Elements 1-2
echo ${fruits[@]:2} # From index 2 to end File I/O & Redirection
6 snippetsReading and writing files
Write to File
echo "Hello" > file.txt # Overwrite
echo "World" >> file.txt # Append Read from File
content=$(cat file.txt)
while read line; do
echo $line
done < file.txt Here Document
cat <<EOF > config.txt
Name: John
Age: 30
EOF Redirect Stderr
command 2> error.log # Stderr to file
command 2>&1 # Stderr to stdout
command &> output.log # Both to file Pipe Output
ls -l | grep ".txt"
cat file.txt | wc -l
ps aux | grep nginx Test File Existence
if [ -f "file.txt" ]; then
cat file.txt
else
echo "File not found"
fi