Lesson 2 of 7 · 9 min · Bash basics
Conditions, loops and functions
What you will learn
if,elif,elsewith the test operators for files, strings and numbers[[ ]]versus[ ]and(( ))casefor matching a value against patternsfor,whileanduntilloops,breakandcontinue- Functions,
localvariables, return codes and returning data
In simple words
So far a script runs straight down, line by line. Real work needs decisions (if the file exists, do this), repetition (do this for every server) and reusable steps you can call by name. This lesson adds those three tools: conditions, loops and functions.
Words to know
- Condition: a test with a yes-or-no answer, used with
ifto choose what to do. - Loop: repeating the same steps, once for each item or until something changes.
- Function: a named block of commands that you can run again and again.
- Exit status: the success or failure number every command leaves behind.
ifreads it.
Conditions are commands
In Bash, if does not test a "boolean". It runs a command and checks its exit code: 0 means true (success), anything else means false.
if grep -q root /etc/passwd; then
echo "root exists"
fi
[[ ... ]], [ ... ] and (( ... )) are just commands built for testing, which is why you need the spaces inside the brackets: [[ $x == y ]] works, [[$x==y]] does not.
Tests with [[ ]]
Prefer [[ ]] in Bash scripts: it does not word-split variables, supports patterns and regular expressions, and allows && and || inside.
file=/etc/passwd
if [[ -f $file && -r $file ]]; then echo "readable file"; fi
File tests: -e exists, -f regular file, -d directory, -r -w -x readable/writable/executable, -s non-empty, -L symlink.
String tests: == and != (right side may be a glob pattern when unquoted), -z empty, -n not empty, =~ regular expression.
[[ "abc" == a* ]] && echo "glob match"
n=7
[[ $n =~ ^[0-9]+$ ]] && echo "is number"
glob match
is number
Numbers: use (( )) for natural arithmetic or the -eq -ne -lt -le -gt -ge operators.
if (( n > 5 )); then echo "n>5"; fi
if [ "$n" -eq 7 ]; then echo "eq 7"; fi
Inside [[ ]], > and < compare strings (so 10 < 9 is true as text). For numbers use (( )) or -lt. The single-bracket [ ] is the old POSIX test command: quote variables inside it, and use -a/-o sparingly; if you need sh compatibility, use it, otherwise use [[ ]].
The shortcut forms
mkdir -p "$dir" && cd "$dir" # run the second only if the first succeeded
cd "$dir" || exit 1 # run the second only if the first failed
[[ -d $1 ]] || { echo "not a directory: $1" >&2; exit 2; }
case: match a value against patterns
case "$1" in
start) echo "starting";;
stop|halt) echo "stopping";;
*) echo "usage: $0 start|stop";;
esac
Each branch ends with ;;, | separates alternatives, and * is the default. Use case for commands and options instead of long if/elif chains. Running with start:
starting
Loops
for i in 1 2 3; do echo -n "$i "; done; echo # 1 2 3
for i in {1..3}; do echo -n "$i "; done; echo # brace expansion, same result
for ((i=0; i<3; i++)); do echo -n "i$i "; done; echo # C style: i0 i1 i2
c=0; while (( c < 3 )); do c=$((c+1)); done; echo "c=$c" # c=3
for x in listloops over words; it is the right loop for a list of servers, files or arguments.while conditionrepeats while the command succeeds.untilrepeats until it succeeds (useful for "wait until the service is up").breakleaves the loop;continuejumps to the next round.
A realistic one, waiting for a service to answer with a time limit:
for attempt in {1..30}; do
if curl -fsS http://localhost:8080/health >/dev/null; then
echo "up after $attempt tries"; break
fi
sleep 2
done
(The -f makes curl fail on HTTP errors and -sS keeps it quiet except for errors. If the loop ends without success, the script should exit non-zero; lesson 3 shows how.)
Looping over files: let the shell expand the glob, do not parse ls.
for f in *.log; do echo "$f"; done # right
for f in $(ls *.log); do ... # wrong: breaks on spaces and odd names
If no file matches, Bash passes the pattern itself (*.log) to the loop. Guard with [[ -e $f ]] || continue, or shopt -s nullglob.
Functions
greet() {
local who="${1:-world}"
echo "hi $who"
return 0
}
greet
greet Asha
hi world
hi Asha
- Arguments inside a function are its own
$1,$2,$@. - Use
localfor variables inside functions. Without it, a variable is global and a function can overwrite the caller's data. return Nsets the function's exit status (0 to 255), nothing more. It cannot return a string or a large number.- To return data, print it and capture it with
$( ):
add() { echo $(( $1 + $2 )); }
sum=$(add 2 3); echo "sum=$sum" # sum=5
- To return success or failure, make the last command a test, and call the function in an
if:
check() { [[ -d $1 ]]; }
check /tmp && echo "/tmp is dir"
check /nope || echo "/nope is not"
/tmp is dir
/nope is not
Functions must be defined before they are called. Keep a script readable: small functions with clear names (usage, log, die, cleanup), then a main function called at the end.
log() { printf '%s %s\n' "$(date +%T)" "$*" >&2; }
die() { log "ERROR: $*"; exit 1; }
Sending logs to stderr (>&2) keeps stdout clean for data that another command may read.
Common mistakes
- No spaces inside brackets.
[[$a==$b]]is a syntax error. - Comparing numbers as strings with
[[ $a > $b ]]. - Unquoted variables in
[ ]:[ $x = y ]fails whenxis empty. Use[[ ]]or quote. - Parsing
lsoutput in aforloop. - Forgetting
local, and wondering why a variable changed. - Treating
returnas a way to hand back text.
Try it yourself
- Write a script that takes a path and says whether it is a file, a directory or missing.
- Write
service.shwithstart,stop,statusbranches usingcase, and a usage message for anything else (exit code 2). - Write a loop that waits up to 60 seconds for a TCP port to open (use
timeout 1 bash -c '</dev/tcp/host/port'), exits 0 when open and 1 on timeout. - Write a function
is_numberthat returns success only for non-negative integers, and use it in anif.
Check yourself
In if grep -q root /etc/passwd; then, what is being tested?
The exit code of grep. 0 (a match was found) is true; 1 (no match) or 2 (error) is false.
What is the difference between [ ] and [[ ]]?
[ ] is the POSIX test command: it needs quoting and spaces and has few features. [[ ]] is a Bash keyword with pattern matching (==, =~), safer handling of unquoted variables and &&/|| inside.
How does a function return a string to its caller?
It prints it, and the caller captures the output with $(function_name). return only sets a numeric status.
Why use local in functions?
Without it the variable is global, so the function could overwrite a variable of the same name in the caller.
Interview questions
What is the difference between while and until?
while repeats as long as the condition command succeeds; until repeats until it succeeds.
How do you run a command only if the previous one succeeded?
cmd1 && cmd2. For "only on failure" use ||. In a script you can also put set -e, covered in lesson 4.
What does (( )) do?
Evaluates an arithmetic expression. As a command, it succeeds (status 0) if the result is non-zero, which makes if (( count > 5 )) natural.
Summary
ifruns a command and tests its exit code (0 = true). Use[[ ]]for strings and files,(( ))for numbers.casematches patterns;forloops over words and globs;while/untilrepeat on a condition.- Functions take
$1.., uselocalfor variables,returnonly a status, and print data for the caller to capture. - Send logs and errors to stderr.
Going deeper
- Bash Reference Manual: Conditional Constructs:
if,case,[[ ]]and(( )). - Bash Reference Manual: Shell Functions: functions,
localand return status. - Bash Guide for Beginners (TLDP): a long, free introduction.
See how much of this you can explain
A free mock interview asks you new questions on Shell scripting with Bash for DevOps Engineer and scores every answer, with what to fix.