87+ examples • Variables, loops, functions • Best practices
name="Alice"
echo "Hello $name"readonly PI=3.14159unset myvarecho "${name:-default}"echo "${name:=default}"echo "${name:+alt}"echo "${#name}"arr=(one two three)
echo "${arr[1]}" # twoecho "${arr[@]}" # all elements
echo "${#arr[@]}" # array lengtharr+=(four five)declare -A map
map[name]="Alice"
map[age]=30
echo "${map[name]}"declare -i num=42echo "${str^^}" # UPPERCASEecho "${str,,}" # lowercaseecho "${str:0:5}" # first 5 charsecho "${str#*.}" # remove prefixecho "${str##*.}" # remove all prefixecho "${str%/*}" # remove suffixecho "${str/old/new}" # first matchecho "${str//old/new}" # all matchesif [[ "$str" == *"pattern"* ]]; then
echo "contains"
fi[[ "$str" =~ ^[0-9]+$ ]] && echo "numeric"if [[ $x -gt 10 ]]; then
echo "big"
elif [[ $x -gt 5 ]]; then
echo "medium"
else
echo "small"
fi[[ -f "file.txt" ]] # file exists
[[ -d "dir" ]] # directory exists
[[ -r "file" ]] # readable
[[ -w "file" ]] # writable
[[ -x "file" ]] # executable
[[ -s "file" ]] # non-empty[[ "$a" == "$b" ]] # string equal
[[ "$a" != "$b" ]] # string not equal
[[ -z "$str" ]] # string is empty
[[ -n "$str" ]] # string not empty[[ $a -eq $b ]] # equal
[[ $a -ne $b ]] # not equal
[[ $a -lt $b ]] # less than
[[ $a -gt $b ]] # greater than
[[ $a -le $b ]] # less or equal
[[ $a -ge $b ]] # greater or equal[[ $a -gt 0 && $a -lt 100 ]][[ $a -eq 0 || $a -eq 1 ]]case "$fruit" in
apple) echo "red" ;;
banana) echo "yellow" ;;
*) echo "unknown" ;;
esacfor i in 1 2 3 4 5; do
echo "$i"
donefor i in {1..10}; do echo "$i"; donefor i in {0..100..5}; do echo "$i"; donefor ((i=0; i<10; i++)); do
echo "$i"
donefor file in *.txt; do
echo "$file"
donewhile [[ $count -lt 10 ]]; do
((count++))
donewhile IFS= read -r line; do
echo "$line"
done < file.txtuntil [[ $status == "ready" ]]; do
sleep 1
status=$(check_status)
donefor i in {1..10}; do
[[ $i -eq 5 ]] && continue
[[ $i -eq 8 ]] && break
echo "$i"
donegreet() {
echo "Hello, $1!"
}
greet "Alice"add() {
local result=$(( $1 + $2 ))
echo $result
}
sum=$(add 3 5) # 8process() {
local name="$1"
local -i count="${2:-1}"
echo "$name x $count"
}cleanup() {
rm -f /tmp/myapp_*
echo "Cleaned up"
}
trap cleanup EXITtrap "echo Interrupted; exit 1" INT TERMdie() {
echo "ERROR: $*" >&2
exit 1
}
[[ -f config ]] || die "No config file"read -p "Enter name: " nameread -sp "Password: " passread -t 5 -p "Quick! " answerecho "hello" > file.txt # overwrite
echo "world" >> file.txt # appendcmd 2>/dev/null # hide errors
cmd &>/dev/null # hide all output
cmd 2>&1 # stderr to stdoutresult=$(command)echo "scale=2; 22/7" | bccat <<EOF
Hello $name
Today is $(date)
EOFprintf "%-10s %5d\n" "$name" "$age"echo $(( 5 + 3 )) # 8
echo $(( 10 % 3 )) # 1
echo $(( 2 ** 10 )) # 1024((count++))
((total += price))if (( x > 10 )); then echo "big"; fiecho "scale=4; 22/7" | bc # 3.1428awk "BEGIN {printf \"%.2f\", 22/7}" # 3.14command &command1 & command2 & waitjobsfg %1nohup command &$$ # current PID
$! # last background PID
$? # last exit codecommand1 && command2command1 || command2(cd /tmp && do_something)grep "pattern" file.txtgrep -r "TODO" --include="*.py" .grep -c "error" log.txtsed 's/old/new/g' file.txtsed -i 's/old/new/g' file.txtsed -n '5,10p' file.txtawk '{print $1, $3}' file.txtawk -F: '{print $1}' /etc/passwdsort file.txt | uniq -c | sort -rncut -d"," -f1,3 data.csvtr "a-z" "A-Z" < file.txtwc -l file.txt#!/usr/bin/env bash
set -euo pipefailset -e # exit on error
set -u # error on unset vars
set -o pipefail # catch pipe errors
set -x # debug (print commands)log() {
echo "[$(date +%Y-%m-%dT%H:%M:%S)] $*"
}SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"[[ $# -lt 2 ]] && { echo "Usage: $0 <src> <dst>"; exit 1; }tmpfile=$(mktemp)
trap "rm -f $tmpfile" EXITif ! command -v jq &>/dev/null; then
echo "jq required"
exit 1
fi# getopts for flags
while getopts "vf:o:" opt; do
case $opt in
v) VERBOSE=1 ;;
f) FILE="$OPTARG" ;;
o) OUTPUT="$OPTARG" ;;
?) exit 1 ;;
esac
doneMade with ♥ by Kas Developer Tools