Learn by reading through in order

Functions — Keeping Repeated Steps in One Place

This article is part of the Linux Course, where you master practical Linux skills from scratch, from basic commands through to shell scripting.
Define logic with name() { ... }, take arguments via $1, keep function-local variables with local, and branch on success with return and $? to reuse the same validation logic — illustrated and practiced in a browser terminal.

Naming a block of logic — defining functions and arguments

Instead of writing the same logic again and again, you can wrap it in a function and call it by name.

Define one with name() { ... }, and put the body between { and }.

After defining it, just write name to run that logic.

This splits a long script into meaningful units, and you only fix things in one place.

To pass values to a function, add arguments after the name when you call it, like name foo bar.

Inside the function, $1 is the first argument and $2 the second (the same notation as the script's own positional parameters).

Wrap an argument in double quotes as "$1", and even a value with spaces is treated as a single argument.

greet() {                        # define a function
  echo "hello, $1"
}
greet alice                      # hello, alice
greet bob                        # hello, bob
How a call maps to arguments
greet alice bob$1 = alice$2 = bobuse $1 $2 in body1st2ndinside greet
The values in greet alice bob go into $1 and $2, and the function body uses them to do its work.
SyntaxMeaningExample
name() { … }Define a functiongreet() { echo "hi $1"; }
name argsCall a functiongreet alice
$1Reference the first argument inside the functionecho "name=$1"
$2Reference the second argument inside the functionecho "port=$2"

Create a utility script that groups input validation into a function and reuses it.

① Open validate.sh with vi validate.sh, press i to enter insert mode, and write #!/bin/sh on the first line.

② Define a function that takes one value, checks whether it is empty, and prints the result. Reference the argument with $1 inside the function.

③ Call the function several times with different values.

④ Press Esc and save with :wq, then add execute permission and run the script to check the result of each call.

⑤ If you are unsure what to write, you can copy the body from the answer panel and paste it into vi's insert mode. (Run it correctly and the explanation will appear.)

Linux console
0 / 3 completed
Loading Linux Terminal...

Variables that live only inside a function — local

When you declare local v=... inside a function, that variable is valid only inside the function and disappears when the function returns.

Without local, you overwrite a variable of the same name outside the function too, which causes unexpected side effects.

To reuse a function safely as a component, make the working variables it uses internally local.

msg="outer"
show() {
  local msg="inner"            # variable only inside the function
  echo "in func: $msg"
}
show                           # in func: inner
echo "outside: $msg"           # outside: outer (unchanged outside)
What local is visible to
msg=outerecho "$msg"prints outerlocal msg=innerecho "$msg"prints innerwhole scriptinside function (local)
A normal variable is visible everywhere, while a local variable is valid only inside the function. Even with the same name, the outer value does not change.
SyntaxMeaningExample
local v=…Create a variable valid only inside the functionlocal step=1
v=…A variable valid across the whole scriptstatus=ready

Create a script that makes a working variable local and confirms it does not affect the outside.

① Open scope.sh with vi scope.sh, press i to enter insert mode, and write #!/bin/sh on the first line.

② Set one variable outside, then define a function that declares a variable of the same name with local and gives it a different value.

③ After calling the function, print the outer variable to confirm its value has not changed.

④ Press Esc and save with :wq, then add execute permission and run the script.

⑤ If you are unsure what to write, you can copy the body from the answer panel and paste it into vi's insert mode.

Linux console
0 / 3 completed
Loading Linux Terminal...

Returning success or failure — return and $?

A function can return an exit code with return N.

By convention 0 means success and anything other than 0 means failure, and right after calling it you can check that value with $?.

Branching directly on a function's success like if check "$x"; then ... makes the flow of validation and processing easier to read.

is_num() {
  case "$1" in
    *[!0-9]*|"") return 1 ;;     # fail if it contains a non-digit or is empty
    *) return 0 ;;
  esac
}
is_num 12; echo "12 -> $?"       # 12 -> 0
is_num abc; echo "abc -> $?"     # abc -> 1
From return to branching on $?
is_num "$1"return 0return 1success pathfailure patha numbernot a number$? = 0 → success$? = 1 → failure
The value from return goes into $?, and if branches treating 0 as success and non-zero as failure.
SyntaxMeaningExample
return 0Leave the function as successis_num 12; # success
return 1Leave the function as failureis_num abc; # failure
$?Check the previous function's return valueis_num 12; echo $?
if name x; then …Branch directly on the return valueif is_num "$v"; then …; fi

Create a function that decides whether a value is a number, and a script that branches on its return value.

① Open isnum.sh with vi isnum.sh, press i to enter insert mode, and write #!/bin/sh on the first line.

② Define a function that checks whether the received value is digits only, returning return 0 if it is a number and return 1 otherwise.

③ Put that function directly in an if condition and print a success or failure message for several inputs.

④ Press Esc and save with :wq, then add execute permission and run the script to check the results.

⑤ If you are unsure what to write, you can copy the body from the answer panel and paste it into vi's insert mode.

Linux console
0 / 3 completed
Loading Linux Terminal...
QUIZ

Knowledge Check

Answer each question one by one.

Q1Which notation references the first argument inside a shell function?

Q2What is the scope of a variable declared with local?

Q3Which one checks the return value of the most recent function?