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 # PortableComments
# Single line comment
: '
Multi-line comment
using colon operator
'Make Executable
chmod +x script.sh
./script.shRun Without Execute Permission
bash script.sh
sh script.shVariables
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 stringsCommand 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 # TimeoutEnvironment Variables
export PATH="/usr/local/bin:$PATH"
export DB_HOST="localhost"
env | grep PATH # View allSpecial Variables
$0 # Script name
$1, $2 # Arguments
$# # Argument count
$@ # All arguments
$? # Last exit status
$$ # Process IDOperators & 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"
fiInteger 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"; fiFile Tests
[ -f file.txt ] # File exists
[ -d /path ] # Directory exists
[ -r file ] # Readable
[ -w file ] # Writable
[ -x file ] # ExecutableLogical 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"
fiTired 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"
fiIf-Else
if [ $score -ge 60 ]; then
echo "Pass"
else
echo "Fail"
fiIf-Elif-Else
if [ $grade -ge 90 ]; then
echo "A"
elif [ $grade -ge 80 ]; then
echo "B"
else
echo "C"
fiCase Statement
case $fruit in
apple)
echo "Red"
;;
banana)
echo "Yellow"
;;
*)
echo "Unknown"
;;
esacTest Syntax [[ ]]
if [[ $name == "John" ]]; then
echo "Hello John"
fi
if [[ $str =~ ^[0-9]+$ ]]; then
echo "Number"
fiLoops
7 snippetsIteration constructs
For Loop (List)
for item in apple banana cherry; do
echo $item
doneFor Loop (Range)
for i in {1..10}; do
echo "Number: $i"
doneFor Loop (C-style)
for ((i=0; i<10; i++)); do
echo $i
doneWhile Loop
count=0
while [ $count -lt 5 ]; do
echo $count
count=$((count + 1))
doneUntil Loop
count=0
until [ $count -ge 5 ]; do
echo $count
count=$((count + 1))
doneLoop Over Files
for file in *.txt; do
echo "Processing: $file"
wc -l "$file"
doneRead Lines from File
while IFS= read -r line; do
echo "Line: $line"
done < file.txtFunctions
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"
fiLocal 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 elementArray Length
echo ${#fruits[@]} # Number of elements
echo ${#fruits[0]} # Length of first elementLoop Through Array
for fruit in "${fruits[@]}"; do
echo $fruit
doneAdd/Remove Elements
fruits+=("orange") # Append
unset fruits[1] # Remove elementArray Slicing
echo ${fruits[@]:1:2} # Elements 1-2
echo ${fruits[@]:2} # From index 2 to endFile I/O & Redirection
6 snippetsReading and writing files
Write to File
echo "Hello" > file.txt # Overwrite
echo "World" >> file.txt # AppendRead from File
content=$(cat file.txt)
while read line; do
echo $line
done < file.txtHere Document
cat <<EOF > config.txt
Name: John
Age: 30
EOFRedirect Stderr
command 2> error.log # Stderr to file
command 2>&1 # Stderr to stdout
command &> output.log # Both to filePipe Output
ls -l | grep ".txt"
cat file.txt | wc -l
ps aux | grep nginxTest File Existence
if [ -f "file.txt" ]; then
cat file.txt
else
echo "File not found"
fi