#!/usr/bin/env bash
set -euo pipefailShebang + strict mode: exit on error, unset vars, failed pipes.
Bash scripting syntax. For individual commands (ls, grep, find…) see the Linux commands cheat sheet.
25 entries
#!/usr/bin/env bash
set -euo pipefailShebang + strict mode: exit on error, unset vars, failed pipes.
name="Ada"
echo "Hello, $name"
echo 'no $expansion here'No spaces around =; double quotes expand, single quotes don’t.
today=$(date +%F)Command substitution.
echo $(( 3 * 4 ))Integer arithmetic.
echo "$0 $1 $# $@ $?"Script name, first arg, arg count, all args, last exit code.
if [[ -f config.yml ]]; then
echo "found"
elif [[ -d config ]]; then
echo "dir"
else
echo "missing"
fiUse [[ ]] in bash.
[[ $a == "$b" ]] [[ $n -gt 5 ]] [[ -z $s ]] [[ $s =~ ^[0-9]+$ ]]String equal, numeric greater, empty, regex match.
command -v jq >/dev/null || echo "install jq"Short-circuit with && and ||.
case "$1" in
start) run ;;
stop|halt) halt ;;
*) echo "usage: $0 start|stop" ;;
esaccase statement.
for f in *.log; do
echo "$f"
doneLoop over files (quote "$f").
for i in {1..5}; do echo "$i"; doneBrace range.
while IFS= read -r line; do
echo "$line"
done < input.txtRead a file line by line safely.
greet() {
local who="${1:-world}"
echo "Hello, $who"
}
greet AdaFunctions take positional args; local scopes variables.
arr=(a b c)
echo "${arr[0]} ${#arr[@]}"
for x in "${arr[@]}"; do echo "$x"; doneIndexed arrays.
declare -A ages=([ada]=36 [alan]=41)
echo "${ages[ada]}"Associative arrays (bash 4+).
${var:-default} ${var:=default}Use default / assign default if unset or empty.
${file%.txt} ${path##*/}Strip suffix; basename.
${s/foo/bar} ${s//foo/bar}Replace first / all.
${#s} ${s:0:3} ${s^^}Length, substring, uppercase.
cmd > out.txt 2>&1
cmd &> out.txtstdout and stderr to a file.
cmd >> log.txtAppend.
cmd 2>/dev/nullDiscard errors.
cat <<EOF
Hello $USER
EOFHere-document.
diff <(sort a.txt) <(sort b.txt)Process substitution.
trap 'rm -f "$tmp"' EXITClean up when the script exits.
Unquoted variables are split on whitespace and glob-expanded, so a file named "my file.txt" becomes two arguments. Quoting ("$var") passes the value intact.
[ ] is the POSIX test command; [[ ]] is a bash keyword that avoids word-splitting surprises and supports && ||, pattern matching and =~ regex. Use [[ ]] in bash scripts.
-e exits on any failing command, -u treats unset variables as errors, and -o pipefail makes a pipeline fail if any command in it fails, not just the last.