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

AWS Cloud

Shell Scripting Complete 6: Bash Functions, local, return and Reusable Script Libraries

Functions give a name to a block of commands so you can reuse it, test it and read the script like a story: check_disk, backup_db, send_alert. This chapter covers defining and calling functions, arguments inside functions, return codes versus output, local variables, returning values with echo and nameref, and building a shared library file that many scripts source. You will also learn a main function, traps for cleanup, and a simple logging library.

In this chapter

  • Define and call functions
  • Use $1, $@ inside functions
  • Know return vs echo
  • Keep variables local
  • Build and source a library
  • Use main and trap for clean scripts

1. An everyday example: a pressure cooker recipe card

Every Pune home has a few fixed steps: 'make tadka' is the same for dal, sabzi and poha. Mother does not explain it each time; she just says 'tadka kar'. A function is that named step. A recipe file shared by the whole family is a library, and each recipe card can just say 'use the tadka step'.

Named step = function. Ingredients you pass = arguments $1 $2. 'Done well' or 'burnt' = return code. The cooked dish = output from echo. Your own bowl = local variable. Family recipe file = library you source.

How a function call worksBash finds the function by nameArguments become $1, $2 inside itlocal variables are createdThe body runsreturn sets the exit code (or the last command does)Back to the caller; $? holds the code
Define a function before you call it.

2. Define and call a function

Pull a small repeated task into a named block. For example, a log() function can receive one message and print it in the same format for the start and end of a report. Defining the function stores the steps. Calling log "report started" runs them with the given text as $1 inside the function. Then call it with a second message and compare the pattern in both lines. This makes one place responsible for the format.

Repeated blocks make scripts long and bugs repeat too. One function means one place to fix.

Write name() { commands; } and call it like a command: name. The keyword form function name { } also works in bash. Names use letters, digits and _. The function must be defined before the line that calls it runs. declare -f name shows its code; type name tells you it is a function.

  1. Define and call.
greet() { echo "Namaskar from $(hostname)"; }; greet

Output:

Namaskar from web01

Called like any command.

  1. See it.
type greet

Output:

greet is a function
greet () 
{ 
    echo "Namaskar from $(hostname)"
}

Bash stored the code.

  1. Called too early.
bash -c 'early; early(){ echo hi; }'

Output:

bash: line 1: early: command not found

Define first.

  1. One-line body needs ;
bad(){ echo x }

Output:

bash: syntax error near unexpected token `}'

Put ; before }.

3. Arguments inside functions

A function that can take a server name or a path works for every server and path.

Inside a function $1, $2, $#, $@ are the function's own arguments, not the script's. To use the script's arguments, pass them in: main "$@". $0 is still the script name; FUNCNAME[0] is the function name. Check required arguments with ${1:?usage} or $#.

  1. Two arguments.
add_user(){ echo "adding $1 to group $2"; }; add_user meera devs

Output:

adding meera to group devs

$1 and $2 belong to the call.

  1. All arguments.
each(){ for x in "$@"; do echo "- $x"; done; }; each 'Pune Camp' Kothrud

Output:

- Pune Camp
- Kothrud

"$@" keeps spaces.

  1. Required.
need(){ local f=${1:?need a file}; echo "using $f"; }; need

Output:

bash: 1: need a file

Stops with a message.

  1. Its own name.
whoami_fn(){ echo "in ${FUNCNAME[0]} with $# args"; }; whoami_fn a b

Output:

in whoami_fn with 2 args

Useful in log lines.

4. return codes vs output

A function has two useful results. It can write a value such as a filename to standard output, and it can return a status saying whether the work succeeded. To use a value in name=$(make_name), have the function print only the value to standard output. Send diagnostic messages to standard error so they stay out of the filename. Add a test where the function returns 1 and see how an if around the assignment can lead to a useful error message.

Beginners try to return text with return. return only gives a number 0-255 meaning success or failure.

return N ends the function with exit code N (0 success). Without return, the code is that of the last command. To give back data, print it with echo or printf and capture it: x=$(fn). Use the code for yes/no and the output for values, so a function can be used both in if and in $( ).

NeedUse
yes/noreturn 0 or 1
a valueecho it, x=$(fn)
many valuesarray via nameref
an error messageecho ... >&2
  1. Yes/no.
is_root(){ [[ $EUID -eq 0 ]]; }; if is_root; then echo root; else echo 'not root'; fi

Output:

not root

The last test is the return code.

  1. Return a value by echo.
disk_pct(){ df --output=pcent "${1:-/}" | tail -1 | tr -dc 0-9; }; p=$(disk_pct /); echo "root at $p%"

Output:

root at 41%

Captured with $( ).

  1. return with text fails.
bad(){ return hello; }; bad

Output:

bash: return: hello: numeric argument required

return takes numbers only.

  1. Over 255 wraps.
f(){ return 300; }; f; echo $?

Output:

44

300 mod 256 = 44.

5. local variables and scope

A function that changes a global variable called i or file can break the caller in strange ways.

By default all variables in bash are global, even those set inside functions. local name=value makes a variable live only inside the function and the functions it calls. Make every helper variable local. Note: local x=$(cmd) hides cmd's exit code; write local x; x=$(cmd) when you need it.

  1. Global leak.
count=10; f(){ count=0; }; f; echo $count

Output:

0

The caller's value changed.

  1. local.
count=10; g(){ local count=0; }; g; echo $count

Output:

10

Caller is safe.

  1. Hidden exit code.
h(){ local out=$(false); echo "code $?"; }; h

Output:

code 0

local itself succeeded.

  1. Correct form.
k(){ local out; out=$(false); echo "code $?"; }; k

Output:

code 1

Now you see the real code.

6. Return several values: nameref and globals

Sometimes a function must fill an array or set two values, and echo is clumsy for that.

local -n ref=$1 (bash 4.3+) makes ref another name for the caller's variable whose name you pass. Assigning to ref changes the caller's variable. Use a clear name (not the same as the caller's) to avoid loops. Older style: set a documented global like RESULT.

  1. Fill a variable.
get_os(){ local -n _out=$1; _out=$(. /etc/os-release; echo $ID); }; get_os os; echo $os

Output:

rhel

The caller's os was set.

  1. Fill an array.
list_users(){ local -n _arr=$1; mapfile -t _arr < <(cut -d: -f1 /etc/passwd | head -3); }; list_users u; echo "${#u[@]}: ${u[*]}"

Output:

3: root bin daemon

Arrays are covered in chapter 7.

  1. Two values by echo and read.
mem(){ free -m | awk '/Mem/{print $2, $3}'; }; read -r total used < <(mem); echo "$used of $total MB"

Output:

3100 of 7820 MB

read splits the output.

7. A main function and script structure

Big scripts are easier to read when the top is settings, the middle is functions and the bottom is one call to main.

Order: shebang, set -euo pipefail, constants, functions, then main "$@" as the last line. Because bash reads the whole file before main runs, functions can be in any order. The guard [[ ${BASH_SOURCE[0]} == $0 ]] && main "$@" runs main only when the file is executed, not when it is sourced (useful for testing).

  1. Skeleton.
cat deploy.sh

Output:

#!/usr/bin/env bash
set -euo pipefail
APP=shop
log(){ echo "[$(date +%T)] $*"; }
build(){ log "building $APP"; }
ship(){ log "shipping to $1"; }
main(){ build; ship "${1:-stage}"; }
main "$@"

Settings, functions, main.

  1. Run it.
./deploy.sh prod

Output:

[10:15:02] building shop
[10:15:02] shipping to prod

main got the script's arguments.

  1. Source guard.
printf 'hi(){ echo hi; }\n[[ ${BASH_SOURCE[0]} == $0 ]] && hi\n' | tee g.sh; source g.sh; bash g.sh

Output:

hi

Sourcing did not run it; executing did.

8. Libraries: source a shared file

A shell library is a file of functions used by more than one script. source reads and runs that file in the current shell. Definitions become available immediately, and commands written outside the definitions run too. Create a test library that defines one harmless function and source it. Check that you can call the function afterward. Keep one-time actions inside named functions so importing the library does not unexpectedly write a report or change your working directory.

Logging, alerts and checks are needed by many scripts. Keep them in one file and load it everywhere.

source file (or . file) runs the file in the current shell, so its functions and variables become available. A library contains only functions and constants, no actions at the top level. Find it relative to the script: source "$(dirname "${BASH_SOURCE[0]}")/lib/common.sh". Prefix function names (log_info, net_check) to avoid clashes. Keep it in git and in /usr/local/lib for servers.

  1. Write a library.
mkdir -p lib; printf 'log_info(){ printf "%%s INFO %%s\\n" "$(date +%%F_%%T)" "$*"; }\nlog_err(){ printf "%%s ERROR %%s\\n" "$(date +%%F_%%T)" "$*" >&2; }\n' | tee lib/common.sh

Only functions, no actions at the top.

  1. Use it.
source lib/common.sh; log_info 'backup started'; log_err 'disk full'

Output:

2026-10-25_10:20:01 INFO backup started
2026-10-25_10:20:01 ERROR disk full

Both functions loaded.

  1. Relative path.
here=$(dirname "${BASH_SOURCE[0]}"); echo "$here/lib/common.sh"

Output:

./lib/common.sh

Works from any folder.

  1. List loaded functions.
declare -F | grep log_

Output:

declare -f log_err
declare -f log_info

declare -F lists names only.

9. trap: cleanup and error handlers

Temp files and lock files must be removed even when the script fails or the user presses Ctrl+C.

trap 'commands' SIGNALS runs commands when the signal arrives. EXIT runs at every end (normal or error). ERR runs when a command fails (with set -E it works inside functions too). INT is Ctrl+C, TERM is kill. Put cleanup in a function: trap cleanup EXIT. $LINENO and $BASH_COMMAND help in error messages.

  1. Cleanup.
bash -c 't=$(mktemp); cleanup(){ rm -f "$t"; echo "removed $t"; }; trap cleanup EXIT; echo work; false; echo never' 

Output:

work
removed /tmp/tmp.Q8x1

Cleanup ran even though false ended nothing here; it runs at every exit.

  1. Error line.
bash -c 'set -eE; trap "echo failed at line \$LINENO: \$BASH_COMMAND" ERR; ls /nope'

Output:

ls: cannot access '/nope': No such file or directory
failed at line 1: ls /nope

Shows which command failed.

  1. Ctrl+C.
trap 'echo " stopping nicely"; exit 130' INT; sleep 100

Output:

^C stopping nicely

Exit 130 = 128 + signal 2.

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
Rutuja, bank ops, PuneShared log library for 40 scriptssource /usr/local/lib/rb/log.sh
James, SaaS, Austinmain "$@" structuremain "$@"
Sakura, retail, Osakatrap cleanup for temp filestrap cleanup EXIT
Karim, oil and gas, Abu Dhabiis_up function used in ifif is_up db1; then
Elena, healthcare, Milanlocal everywhere in helperslocal f=$1
Ganesh, telecom, HyderabadNameref to return arrayslocal -n out=$1

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
command not found for my functionCalled before definedDefine first or use main at the end.
main "$@"
syntax error near unexpected token `}'Missing ; before } on one lineAdd ;.
f(){ echo x; }
numeric argument requiredreturn with textecho the value instead.
echo "$val"
Caller's variable changedNot localUse local.
local i
$1 is empty in the functionScript args not passedCall with "$@".
main "$@"
No such file when sourcing libraryPath relative to current folderUse BASH_SOURCE.
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
Error code lostlocal x=$(cmd)Split declare and assign.
local x; x=$(cmd)
circular name referencenameref same name as caller varUse a unique ref name.
local -n _ref=$1
Temp files left after Ctrl+CNo trapAdd trap cleanup EXIT.
trap cleanup EXIT

12. Troubleshooting step by step

See which functions exist, trace calls and check return codes.

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

  1. List functions.
declare -F
  1. Show one.
declare -f log_info
  1. Trace with function names.
PS4='+${FUNCNAME[0]:-main}:$LINENO: ' bash -x s.sh
  1. Call stack.
echo "${FUNCNAME[*]}"
  1. Return code.
myfn; echo $?
  1. Lint.
shellcheck s.sh lib/*.sh

13. Lab 1: Build a small library

Create lib/ops.sh with log, die and need_cmd functions, then use it from two scripts.

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

  1. Folder.
mkdir -p ~/lab42/lib && cd ~/lab42
  1. Library.
printf 'log(){ echo "[$(date +%%T)] $*"; }\ndie(){ echo "FATAL: $*" >&2; exit 1; }\nneed_cmd(){ command -v "$1" &>/dev/null || die "$1 not installed"; }\n' | tee lib/ops.sh
  1. Script A.
printf '#!/bin/bash\nsource "$(dirname "$0")/lib/ops.sh"\nneed_cmd tar\nlog "tar is ready"\n' | tee a.sh && chmod +x a.sh && ./a.sh

Output:

[10:30:11] tar is ready
  1. Script B fails nicely.
printf '#!/bin/bash\nsource "$(dirname "$0")/lib/ops.sh"\nneed_cmd nosuchtool\n' | tee b.sh && chmod +x b.sh && ./b.sh; echo $?

Output:

FATAL: nosuchtool not installed
1
  1. Run from elsewhere.
cd /tmp && ~/lab42/a.sh

Output:

[10:30:20] tar is ready
  1. List functions.
bash -c 'source ~/lab42/lib/ops.sh; declare -F'

Output:

declare -f die
declare -f log
declare -f need_cmd

14. Lab 2: main, local and trap together

Write report.sh with a main function, local variables, a value-returning function and a trap that removes the temp file.

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

  1. Write.
cd ~/lab42 && printf '#!/usr/bin/env bash\nset -euo pipefail\ntmp=$(mktemp)\ncleanup(){ rm -f "$tmp"; echo "cleaned"; }\ntrap cleanup EXIT\ncount_files(){ local d=$1; find "$d" -maxdepth 1 -type f | wc -l; }\nmain(){ local dir=${1:-/etc}; local n; n=$(count_files "$dir"); echo "$dir has $n files" | tee "$tmp"; }\nmain "$@"\n' | tee report.sh && chmod +x report.sh
  1. Run.
./report.sh /etc

Output:

/etc has 94 files
cleaned
  1. Default.
./report.sh

Output:

/etc has 94 files
cleaned
  1. Failure still cleans.
./report.sh /nope; echo $?

Output:

find: '/nope': No such file or directory
cleaned
1
  1. Temp gone.
ls /tmp/tmp.* 2>/dev/null | wc -l

Output:

0
  1. dir stayed local.
bash -c 'source <(sed "\$d" report.sh); main /tmp; echo "[${dir:-}]"'

Output:

/tmp has 3 files
[]
cleaned

Ravindra Bagale's Tip

Make every variable inside a function local, use return only for success or failure, and echo the data you want to give back. Put shared functions in a library and source it with a path built from BASH_SOURCE.

15. Frequently asked questions

Q. name() or function name?

Both in bash; name() is portable.

Q. Can functions call each other?

Yes, and themselves (recursion).

Q. How to return a string?

echo it and use $( ).

Q. Does $( ) slow things down?

It forks a subshell; fine for most scripts.

Q. source vs running a script?

source runs in the current shell.

Q. Export a function to child scripts?

export -f name.

Q. Unset a function?

unset -f name.

Q. Where to keep libraries?

Repo lib/ or /usr/local/lib.

16. Interview questions and answers

Beginner level

Q. Define a function?

name() { ...; }.

Q. First argument in a function?

$1.

Q. Load a library?

source file.

Q. Function exit code?

return N or last command.

Mid level level

Q. return vs echo?

Code vs data.

Q. Why local?

Avoid changing globals.

Q. What does trap EXIT do?

Runs cleanup on any exit.

Q. Pass script args to main?

main "$@".

Senior level

Q. Design a shared bash library?

Prefixed functions, no top-level actions, source guard, versioned, shellcheck in CI.

Q. local x=$(cmd) issue?

Masks exit code; split it.

Q. Return arrays?

nameref local -n or print lines with mapfile.

Q. Make scripts testable?

Functions + source guard; test with bats.

Try at home

  1. Write a function is_port_open HOST PORT that returns 0 or 1 and use it in an if.
  2. Move it into lib/net.sh and source it from two different scripts.

Practise this chapter

Interview questions and answers

How would you return a filename from a function and still log a problem?

Print the filename alone to standard output. Send diagnostics to standard error and return a distinct failure status when needed. Then capture the value only on success. This allows another script to use the filename without treating a log line as part of it.

Check your understanding

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

0 of 3 answered correctly
1. What does defining a Bash function do before it is called?

Answer and explanation

B. Makes its named instructions available without running the function body

The function definition registers the commands. A later call supplies arguments and runs them.

2. What does sourcing a shared function file do to commands at its top level?

Answer and explanation

B. Runs them in the current shell

source reads and executes the file in the current shell. Keep unwanted effects out of top-level commands.

3. Which channel is best for a diagnostic when stdout is captured as a filename?

Answer and explanation

C. Standard error

Keeping diagnostics on stderr lets a caller capture only the intended data from stdout.

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

Ahmednagar Sugar Co-op is a sugar co-operative business in Ahilyanagar. Balasaheb Pawar 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 Define

Shared functions keep BIZ scripts short and consistent.

Define a function hello that prints Namaste on one line.

  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 it a function

Shared functions keep BIZ scripts short and consistent.

Show what kind of command backup_now is.

  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 List functions

Shared functions keep BIZ scripts short and consistent.

List the names of all defined functions with compgen.

  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 Local variable

Shared functions keep BIZ scripts short and consistent.

Inside a function, make a local variable dir set to the first 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.

Easy Return failure

Shared functions keep BIZ scripts short and consistent.

Return failure with code 1 from a function.

  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 Call run_all

Shared functions keep BIZ scripts short and consistent.

Call run_all passing all script arguments.

  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 Load a library

Shared functions keep BIZ scripts short and consistent.

Load lib/alerts.sh into the current shell.

  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 List traps

Shared functions keep BIZ scripts short and consistent.

Show the traps that are currently set.

  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 Show code

Shared functions keep BIZ scripts short and consistent.

Show the code of the function send_sms.

  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 Capture output

Shared functions keep BIZ scripts short and consistent.

Store the output of the function get_ip into addr.

  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 Function in if

Shared functions keep BIZ scripts short and consistent.

Run is_weekend in an if and print rest when it returns success.

  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 Required arg

Shared functions keep BIZ scripts short and consistent.

Inside a function, set local f to $1 or stop with "need path".

  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 Export a function

Shared functions keep BIZ scripts short and consistent.

Export the function notify to child shells.

  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 Remove a function

Shared functions keep BIZ scripts short and consistent.

Delete the function old_sync.

  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 Function name

Shared functions keep BIZ scripts short and consistent.

Inside a function, print its own name.

  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 Cleanup trap

Shared functions keep BIZ scripts short and consistent.

Run the function tidy whenever the script exits.

  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 Ctrl+C trap

Shared functions keep BIZ scripts short and consistent.

On Ctrl+C print bye and exit 130.

  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 Keep the code

Shared functions keep BIZ scripts short and consistent.

Declare local out first, as a separate statement, before assigning command output to it.

  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 Relative library

Shared functions keep BIZ scripts short and consistent.

Source helpers.sh from the same folder as the running script, using BASH_SOURCE.

  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 Nameref

Shared functions keep BIZ scripts short and consistent.

Inside a function, make _dst a name reference to the variable named in $1.

  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 Error trap

Shared functions keep BIZ scripts short and consistent.

Make the ERR trap work inside functions too, together with exit-on-error.

  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. name(){ ...; } defines; call it by name.
  2. $1, $@ inside are the function's arguments.
  3. return gives a code; echo gives data.
  4. local keeps variables private.
  5. source loads a library into the current shell.
  6. main "$@" last, trap cleanup EXIT for safety.

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.

Functions in 4 steps. Define: name() { }. Args are $1, $2 inside. Use local for variables. Status with return.
Revision card: Functions in 4 steps · Download PNG · Open card page
Script library. Put helpers in one file. Only functions inside. Load it. Call main last.
Revision card: Script library · Download PNG · Open card page
return vs exit. Leaves the function. / Ends the whole script.
Comparison: return vs exit · Download PNG · Open card page
source vs ./script. Same shell. / New child shell.
Comparison: source vs ./script · Download PNG · Open card page
return vs echo in a function?. return gives a status 0-255. echo gives data to capture. Capture.
Interview card: return vs echo in a function? · Download PNG · Open card page
Why local?. Variables are global by default. local keeps them inside. Example.
Interview card: Why local? · Download PNG · Open card page
source vs ./script?. source runs in the current shell. ./script starts a new shell. Load helpers.
Interview card: source vs ./script? · Download PNG · Open card page
Clean up on exit?. trap runs code on signals. EXIT fires on any end. Example.
Interview card: Clean up on exit? · Download PNG · Open card page

More cards: Ravi Sir's Cards.