Bash Functions and Script Arguments
Functions group commands under one name, so you can reuse them instead of copying code.
Creating a Function
Define the function first, then call it by its name, like any command:
Example
greet() {
echo "Welcome to Workownix!"
}
greet
greetWelcome to Workownix! Welcome to Workownix!
You may also see the style function greet { ... }. Both work in Bash.
Function Arguments
Arguments are not written in the brackets. Inside the function they arrive as $1, $2 and so on.
Example
bill() {
local item=$1
local price=$2
local qty=$3
echo "$qty x $item = Rs $((price * qty))"
}
bill "Samosa" 40 5
bill "Chai" 60 25 x Samosa = Rs 200 2 x Chai = Rs 120
| Variable | Holds |
|---|---|
$1, $2, ... | The first, second, ... argument |
$# | The number of arguments |
$@ | All the arguments |
$0 | The name of the script |
Local Variables
Variables in Bash are global by default, even inside functions. Use local to keep a variable inside its function:
Example
name="Ali"
change() {
local name="Sara"
echo "Inside: $name"
}
change
echo "Outside: $name"Inside: Sara Outside: Ali
Use local for every variable inside a function. It stops your functions from changing values elsewhere in the script by accident.
Returning Values
return in Bash only gives an exit code, a number from 0 to 255. Zero means success. To give back real data, echo it and catch it with $( ):
Example
square() {
echo $(( $1 * $1 ))
}
is_even() {
if [ $(( $1 % 2 )) -eq 0 ]; then
return 0
else
return 1
fi
}
result=$(square 9)
echo "9 squared is $result"
if is_even 14; then
echo "14 is even"
fi
is_even 7
echo "Exit code: $?"9 squared is 81 14 is even Exit code: 1
$? holds the exit code of the last command.
Script Arguments
A script receives arguments the same way. Save this as welcome.sh:
Example
#!/bin/bash
if [ "$#" -lt 1 ]; then
echo "Usage: $0 name [name...]"
exit 1
fi
echo "You gave $# name(s)."
for person in "$@"; do
echo "Hello, $person"
doneRun it with two names:
Example
bash welcome.sh Ayesha BilalYou gave 2 name(s). Hello, Ayesha Hello, Bilal
exit 1 stops the script with an error code. Scripts that finish normally exit with 0.
A Practical Example
This function makes a dated backup copy of any file:
Example
backup() {
local file=$1
if [ ! -f "$file" ]; then
echo "No such file: $file"
return 1
fi
cp "$file" "$file.$(date +%Y%m%d).bak"
echo "Backed up $file"
}
backup notes.txtIf notes.txt exists, it is copied to a name like notes.txt.20261015.bak.
Exercise
Exercise
Inside a Bash function, which variable holds the first argument?
