Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

Shell Scripting Complete 4: if, else, test, [[ ]], (( )) and case Explained Simply

Scripts need to make decisions: is the disk full, does the file exist, did the command work, which environment are we in? This chapter teaches if, elif and else, the test command and [ ], the safer bash [[ ]], number and string comparisons, file tests, regex matching with =~, && and || shortcuts, (( )) for numbers, and case for menus and many choices.

In this chapter

  • Write if / elif / else
  • Know that if checks an exit code
  • Compare numbers and strings correctly
  • Use file tests -f -d -r -s
  • Prefer [[ ]] and use =~
  • Use case for many choices

1. An everyday example: a traffic signal

At a signal you decide: if red, stop; else if yellow, slow down; else go. A traffic police officer at a big junction does the same with many roads: case road 1, case road 2, case road 3. Scripts decide in the same way, using tests that answer yes or no.

Light colour = the value. Checking the colour = test or [[ ]]. Stop/slow/go = if, elif, else. Junction with many roads = case. Yes/no answer = exit code 0 or non-zero.

How if worksRun the command after ifLook at its exit code0 means true: run the then partNon-zero: try the elif testsNothing matched: run elsefi ends the block
[ ] runs the test command, while [[ ]] is Bash syntax. A valid test returns 0 for true or 1 for false. Invalid input can have a different status.

2. if, then, elif, else, fi

An if uses the exit status of a command as its decision. Start with a disposable file called report.txt. The test if [ -f report.txt ]; then ... succeeds when that path is a regular file, so the first branch runs. Move your file out of the way and repeat the test to see the other branch. Nothing has to be printed for a test to succeed. The shell follows the status and runs the commands inside the selected branch.

Without decisions a script does the same thing even when something has gone wrong.

if COMMAND; then ...; elif COMMAND; then ...; else ...; fi. If runs any command and checks its exit code: 0 is true. So you can write if grep -q x file; then. The ; before then can be a new line instead. Indent the body by two or four spaces.

  1. Command as the test.
if ping -c1 -W1 8.8.8.8 &>/dev/null; then echo online; else echo offline; fi

Output:

online

ping returned 0.

  1. Three branches.
hour=$(date +%H); if [ $hour -lt 12 ]; then echo 'Good morning'; elif [ $hour -lt 17 ]; then echo 'Good afternoon'; else echo 'Good evening'; fi

Output:

Good evening

Only the first true branch runs.

  1. grep -q.
if grep -q '^asha:' /etc/passwd; then echo 'user exists'; fi

Output:

user exists

-q prints nothing, only the exit code matters.

  1. Negate.
if ! systemctl is-active -q nginx; then echo 'nginx is down'; fi

Output:

nginx is down

! flips true and false.

3. test and [ ]: numbers

Disk percent, error counts and retry numbers need comparisons.

[ is the test command; the closing ] is required and spaces inside are required: [ $a -gt 5 ]. Number operators are words: -eq equal, -ne not equal, -lt less, -le less or equal, -gt greater, -ge greater or equal. Do not use < or > inside [ ] for numbers: they mean redirection there.

OperatorMeans
-eqequal
-nenot equal
-lt / -leless / less or equal
-gt / -gegreater / greater or equal
  1. Disk alert.
use=$(df --output=pcent / | tail -1 | tr -dc 0-9); if [ "$use" -ge 90 ]; then echo "ALERT $use%"; else echo "ok $use%"; fi

Output:

ok 41%

tr -dc 0-9 keeps only the digits.

  1. Spaces matter.
[$use -ge 90]

Output:

bash: [41: command not found

[ must be a separate word.

  1. test is the same.
test 5 -gt 3 && echo yes

Output:

yes

[ ] is just another way to write test.

  1. Empty variable trap.
x=; [ $x -eq 1 ]

Output:

bash: [: -eq: unary operator expected

Quote it or give a default.

4. String tests: =, !=, -z, -n

Checking environment names, answers and empty values is everyday work.

[ "$a" = "$b" ] equal, != not equal. -z "$a" true if empty, -n "$a" true if not empty. Always quote variables inside [ ] or an empty value breaks the test. Inside [[ ]] (next section) == also works and quoting is less critical.

  1. Equal.
env=prod; if [ "$env" = prod ]; then echo 'careful: production'; fi

Output:

careful: production

Strings compared exactly.

  1. Empty check.
name=''; [ -z "$name" ] && echo 'name is empty'

Output:

name is empty

-z means zero length.

  1. Not empty.
[ -n "$HOME" ] && echo "home set: $HOME"

Output:

home set: /home/asha

-n means non-zero length.

  1. Case matters.
[ Prod = prod ] || echo different

Output:

different

Compare ${v,,} to ignore case.

5. File tests: -e -f -d -r -w -x -s

Choose a file test that answers your actual question. For an upload script, -e answers whether a path exists, while -f asks whether it is a regular file. -s asks whether it has a size greater than zero. Set up a small test with a missing path, a directory, an empty file and a nonempty file. Predict which tests succeed for each. Once the results match, combine the checks you need and give the user a specific error for the first failed condition.

Before reading, copying or deleting you should know the file is there and is the right type.

-e exists. -f regular file. -d directory. -L symlink. -r readable, -w writable, -x executable by you. -s exists and is not empty. a -nt b means a is newer than b; -ot older.

TestTrue when
-eexists
-fregular file
-ddirectory
-ssize > 0
-r/-w/-xyou can read/write/run
-ntnewer than
  1. Config exists?
conf=/etc/ssh/sshd_config; if [ -f "$conf" ]; then echo found; else echo missing; fi

Output:

found

A regular file.

  1. Make a folder if missing.
[ -d /tmp/reports ] || mkdir -p /tmp/reports; ls -d /tmp/reports

Output:

/tmp/reports

|| runs only when the test fails.

  1. Empty file.
: > /tmp/e.txt; [ -s /tmp/e.txt ] || echo 'file is empty'

Output:

file is empty

-s needs at least one byte.

  1. Newer.
[ /etc/hosts -nt /etc/hostname ] && echo 'hosts changed later'

Output:

hosts changed later

Compares modification times.

6. [[ ]]: the safer bash test

[ ] has traps with empty values and special characters. [[ ]] is built into bash and avoids most of them.

[[ ]] does not split words or expand globs on variables, so an empty $x is safe. It supports && and || inside, == with patterns ([[ $f == *.log ]]), < and > for string order, and =~ for regex. It works in bash, not in plain sh. In bash scripts, use [[ ]] for strings and files and (( )) for numbers.

Feature[ ][[ ]]
empty var unquotedbreakssafe
&& || insideno (use -a -o)yes
pattern ==noyes
regex =~noyes
POSIX shyesno
  1. Pattern.
f=app-2026.log; [[ $f == *.log ]] && echo 'a log file'

Output:

a log file

* is a pattern here, not a file list.

  1. Two conditions.
age=25; city=Pune; [[ $age -ge 18 && $city == Pune ]] && echo 'can vote in Pune'

Output:

can vote in Pune

&& works inside.

  1. Empty is safe.
x=; [[ $x == yes ]] || echo 'not yes'

Output:

not yes

No error with an empty value.

  1. String order.
[[ apple < banana ]] && echo 'apple comes first'

Output:

apple comes first

< compares alphabetically.

7. Regex with =~ and BASH_REMATCH

Validating an email, a version number or an IP needs a pattern, not just equality.

[[ $s =~ regex ]] is true when the regex matches. Do not quote the regex (quotes make it literal); store it in a variable if it has spaces. Groups in ( ) are saved in the BASH_REMATCH array: ${BASH_REMATCH[1]} is the first group.

  1. Indian PIN code.
pin=411045; [[ $pin =~ ^[1-9][0-9]{5}$ ]] && echo 'valid PIN'

Output:

valid PIN

Six digits, not starting with 0.

  1. Extract the version.
v='nginx/1.24.0'; [[ $v =~ ([0-9]+)\.([0-9]+) ]] && echo "major=${BASH_REMATCH[1]} minor=${BASH_REMATCH[2]}"

Output:

major=1 minor=24

Groups are saved.

  1. Regex in a variable.
re='^[a-z]+@[a-z]+\.[a-z]+$'; [[ ravi@shop.in =~ $re ]] && echo 'looks like email'

Output:

looks like email

Unquoted $re is used as a regex.

8. && and || shortcuts, and (( )) for numbers

Short checks read better on one line, and number checks are easier with normal maths signs.

a && b runs b only if a worked. a || b runs b only if a failed. Be careful with a && b || c: c also runs if b fails, so use a full if when b can fail. (( expr )) is true when the result is not 0, and you can use < > == != with numbers: (( count > 10 )).

  1. Run only if it worked.
mkdir -p /tmp/deploy && cd /tmp/deploy && pwd

Output:

/tmp/deploy

Stops at the first failure.

  1. Fallback.
cd /no/such/dir 2>/dev/null || echo 'could not cd, stopping'

Output:

could not cd, stopping

|| handles the failure.

  1. Numbers the easy way.
errors=12; if (( errors > 10 )); then echo 'too many errors'; fi

Output:

too many errors

No -gt needed.

  1. Even or odd.
n=7; (( n % 2 == 0 )) && echo even || echo odd

Output:

odd

% is remainder.

9. case: many choices in a clean way

A menu often has one value and several known choices. In a lab script, let case "$1" send status to a read-only check, help to usage, and anything else to a clear error. Try status, help and a spelling mistake as separate runs. The first matching branch runs, so put the fallback pattern * last. Keep the three expected outputs in view while you practise.

A chain of ten elifs comparing the same variable is hard to read. case is cleaner and supports patterns.

case $x in pattern1) ...;; pattern2|pattern3) ...;; *) default;; esac. Patterns are globs: *.jpg, [yY]*, start|begin. ;; ends each branch. The first match wins, so put *) last. Very common for start/stop/status menus and for file types.

  1. Service menu.
act=restart; case $act in start) echo starting;; stop) echo stopping;; restart|reload) echo 'stop then start';; *) echo "usage: start|stop|restart";; esac

Output:

stop then start

| gives two names to one branch.

  1. By extension.
f=photo.JPG; case ${f,,} in *.jpg|*.png) echo image;; *.pdf) echo document;; *) echo other;; esac

Output:

image

${f,,} makes it lower case first.

  1. Yes/no.
ans=Yes; case $ans in [yY]*) echo ok;; *) echo no;; esac

Output:

ok

[yY]* matches y, Y, yes, Yes.

  1. Weekday.
case $(date +%u) in 6|7) echo weekend;; *) echo 'work day';; esac

Output:

weekend

date +%u gives 1-7.

10. Real examples from many industries

The same Linux skill shows up in every kind of company. Seeing it in many places helps you remember it.

Each row is a made-up team. It shows who uses this and how.

Team and cityHow they use itCommand
Sneha, hospital, PuneAlert when disk >= 90(( use >= 90 ))
Liam, bank, SydneyStop if not on prod host[[ $(hostname) == prod-* ]]
Yuki, gaming, TokyoVersion check with =~[[ $v =~ ^2\. ]]
Fatima, telecom, Dubaistart/stop menu with casecase $1 in start)
Lucas, logistics, São PauloSkip empty CSV files[ -s "$f" ] || continue
Anil, manufacturing, AurangabadRestart only if downsystemctl is-active -q x || systemctl restart x

11. Common errors and how to fix them

Everyone hits these errors. Knowing the cause saves hours.

Read the exact message first. Then match it to a row below.

Error you seeWhy it happensHow to fix
[: missing `]'No space before ]Add spaces inside brackets.
[ "$a" = b ]
[41: command not foundNo space after [Write [ $x ...
[ "$x" -gt 5 ]
unary operator expectedEmpty unquoted variableQuote or use [[ ]].
[[ $x -eq 1 ]]
integer expression expectedText used with -gtCheck it is a number.
[[ $x =~ ^[0-9]+$ ]]
A file named 5 appearedUsed > in [ ] for numbersUse -gt or (( )).
(( a > 5 ))
syntax error near unexpected token `fi'Missing thenAdd then.
if x; then y; fi
syntax error near unexpected token `)' in caseMissing ;; or inEnd each branch with ;;.
case $a in x) y;; esac
Regex never matchesRegex was quotedRemove quotes or use a variable.
[[ $s =~ $re ]]
[[: not foundScript run with shUse bash or #!/bin/bash.
bash s.sh

12. Troubleshooting step by step

Print the values being compared, then run the test alone and look at $?.

Go top to bottom. Stop at the first step that shows the problem.

  1. See the values.
echo "[$a] [$b]"
  1. Test alone.
[[ $a == $b ]]; echo $?
  1. Trace.
bash -x s.sh
  1. Lint.
shellcheck s.sh
  1. Which shell?
head -1 s.sh
  1. Hidden \r from Windows.
cat -A s.sh | grep -m3 '\^M'

13. Lab 1: A health check with if and file tests

Write health.sh that checks disk, a config file and a service, and prints OK/WARN/FAIL lines.

A full hands-on lab. Run every step on a test Linux machine (an EC2 instance, a VM, or WSL).

  1. Folder.
mkdir -p ~/lab40 && cd ~/lab40
  1. Disk part.
use=$(df --output=pcent / | tail -1 | tr -dc 0-9); if (( use >= 90 )); then echo "FAIL disk $use%"; elif (( use >= 75 )); then echo "WARN disk $use%"; else echo "OK disk $use%"; fi

Output:

OK disk 41%
  1. Config part.
f=/etc/ssh/sshd_config; [[ -r $f ]] && echo "OK $f readable" || echo "FAIL $f"

Output:

OK /etc/ssh/sshd_config readable
  1. Service part.
if systemctl is-active -q sshd; then echo 'OK sshd'; else echo 'FAIL sshd'; fi

Output:

OK sshd
  1. Empty log check.
touch app.log; [[ -s app.log ]] || echo 'WARN app.log is empty'

Output:

WARN app.log is empty
  1. Exit code.
bash -c 'exit 0'; echo $?

Output:

0

14. Lab 2: A case-based service tool

Build svc.sh start|stop|status|-h for a fake service, with pattern matching and a usage message.

A full hands-on lab. Run every step on a test Linux machine (an EC2 instance, a VM, or WSL).

  1. Write.
printf '#!/bin/bash\ncase ${1:-} in\n  start) touch /tmp/svc.pid; echo started;;\n  stop) rm -f /tmp/svc.pid; echo stopped;;\n  status) [[ -e /tmp/svc.pid ]] && echo running || echo stopped;;\n  -h|--help|"") echo "usage: $0 start|stop|status";;\n  *) echo "unknown: $1" >&2; exit 2;;\nesac\n' | tee svc.sh && chmod +x svc.sh
  1. Start.
./svc.sh start; ./svc.sh status

Output:

started
running
  1. Stop.
./svc.sh stop; ./svc.sh status

Output:

stopped
stopped
  1. Help.
./svc.sh

Output:

usage: ./svc.sh start|stop|status
  1. Bad input.
./svc.sh boom; echo $?

Output:

unknown: boom
2
  1. Lint it.
shellcheck svc.sh && echo clean

Output:

clean

Ravindra Bagale's Tip

In bash scripts use [[ ]] for strings and files, (( )) for numbers, and case when you compare one value against many choices. Remember: if only looks at an exit code, so any command can be a test.

15. Frequently asked questions

Q. [ ] or [[ ]]?

[[ ]] in bash; [ ] for POSIX sh.

Q. Why spaces inside brackets?

[ is a command; its args need spaces.

Q. = or ==?

Both in [[ ]]; = in [ ].

Q. How to test 'not'?

Put ! before the test.

Q. Can case use regex?

No, only glob patterns.

Q. Is (( 0 )) true?

No; 0 is false there.

Q. Compare decimals?

Use awk or bc.

Q. What is ;;& in case?

Continues testing next patterns (bash 4).

16. Interview questions and answers

Beginner level

Q. Number greater than?

-gt or (( > )).

Q. File exists?

-e or -f.

Q. String empty?

-z.

Q. End an if?

fi.

Mid level level

Q. [ ] vs [[ ]]?

[[ ]] is safer, supports patterns, regex, && ||.

Q. When case over if?

Many choices on one value.

Q. Danger of a && b || c?

c runs if b fails too.

Q. Get regex groups?

BASH_REMATCH.

Senior level

Q. Why does if grep work?

if checks exit codes; grep returns 0 on match.

Q. Write portable tests?

Use [ ] with quoted vars and = only.

Q. Validate an IPv4 roughly?

=~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ plus range checks.

Q. Guard against running on prod?

[[ $(hostname) == prod* ]] && read confirmation.

Try at home

  1. Write grade.sh that takes marks (0-100) and prints A/B/C/Fail with if/elif. Reject bad input.
  2. Write ftype.sh that uses case to say image, video, document or other for each argument.

Practise this chapter

Interview questions and answers

Why would an if branch run even when the test prints nothing?

Bash chooses the branch based on the test’s exit status. Use a simple file test and repeat after moving the disposable file out of the way. Show the two branches and explain what changed rather than expecting the test itself to print true or false.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. Which condition specifically tests for a regular file?

Answer and explanation

C. [ -f "$path" ]

The f test asks for a regular file. The e test checks existence broadly, and d checks for a directory.

2. A script needs an input file to contain data. Which test checks its size is above zero?

Answer and explanation

B. -s

The s test checks file size. z tests an empty string and x tests permission to execute or search.

3. Where should a case branch matching * appear in this menu?

Answer and explanation

A. After the specific choices

The first matching pattern wins. A broad fallback before the named choices would take all inputs.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Amravati Agro Market is a agriculture business in Amravati. Anjali Thakre looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 21

Easy At least 80

BIZ scripts must decide before they act.

Test with [ ] that the variable cpu is greater than or equal to 80.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Not equal number

BIZ scripts must decide before they act.

Test that the variable rc is not equal to 0 with [ ].

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Less than 5

BIZ scripts must decide before they act.

Test with (( )) that tries is less than 5.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Empty?

BIZ scripts must decide before they act.

Test with [ ] that the variable reply is empty.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Not empty

BIZ scripts must decide before they act.

Test with [[ ]] that the variable sku is not empty.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy String equal

BIZ scripts must decide before they act.

Test with [ ] that the variable tier equals gold.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Is a folder

BIZ scripts must decide before they act.

Test that /srv/invoices is a directory.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Is a file

BIZ scripts must decide before they act.

Test that /etc/nginx/nginx.conf is a regular file.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Empty answer

BIZ scripts must decide before they act.

Using [[ ]] and &&, print empty when the variable ans has zero length.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Executable

BIZ scripts must decide before they act.

Test that /usr/local/bin/sync-erp is executable by you.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Not empty file

BIZ scripts must decide before they act.

Test that orders.json exists and is not empty.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Writable folder

BIZ scripts must decide before they act.

Test that /var/backups is writable, else print "no write".

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Pattern match

BIZ scripts must decide before they act.

Test with [[ ]] that the variable img ends in .webp.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Two conditions

BIZ scripts must decide before they act.

In one [[ ]] test that age is at least 21 and city is Nagpur.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium If grep

BIZ scripts must decide before they act.

Write an if that checks quietly whether /etc/group has a line starting with docker: and prints yes.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Not active

BIZ scripts must decide before they act.

Print "redis down" if the redis service is not active, quietly using systemctl.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Odd

BIZ scripts must decide before they act.

Use (( )) and && to print odd when n leaves remainder 1 on division by 2.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium case on second

BIZ scripts must decide before they act.

Start a case statement on the second argument.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Hard Newer file

BIZ scripts must decide before they act.

Test that build.tar is newer than src.tar.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Hard Regex

BIZ scripts must decide before they act.

Test with =~ that the variable gstin starts with two digits.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Hard Starts with n

BIZ scripts must decide before they act.

Using [[ ]] with a bracket pattern, print skip when ans starts with n or N.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

In short

  1. if checks an exit code; 0 is true.
  2. [ ] needs spaces and quoted vars.
  3. -eq -lt -gt for numbers; = != -z -n for strings.
  4. -f -d -s -r -w -x for files.
  5. [[ ]] adds patterns, regex and && ||.
  6. case handles many choices with patterns.

Revision, comparison and interview cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

if in 4 steps. if runs a test. Exit code 0 = true. Strings and patterns: [[ ]]. Numbers: (( )).
Revision card: if in 4 steps · Download PNG · Open card page
File tests. -f regular file. -d directory. -s not empty. Example.
Revision card: File tests · Download PNG · Open card page
[ ] vs [[ ]]. POSIX, quote everything. / Bash, safer word handling.
Comparison: [ ] vs [[ ]] · Download PNG · Open card page
if/elif vs case. Any tests, any mix. / One value, many patterns.
Comparison: if/elif vs case · Download PNG · Open card page
[ ] vs [[ ]]?. [ ] is POSIX test. [[ ]] is bash: safer, patterns, regex. Regex.
Interview card: [ ] vs [[ ]]? · Download PNG · Open card page
Compare numbers?. (( )) uses < > ==. In [ ] use -lt -gt -eq. Example.
Interview card: Compare numbers? · Download PNG · Open card page
&& and || as if?. a && b: b runs if a worked. a || b: b runs if a failed. Example.
Interview card: && and || as if? · Download PNG · Open card page
When to use case?. Many choices on one value. Patterns with * and |. Start.
Interview card: When to use case? · Download PNG · Open card page

More cards: Ravi Sir's Cards.