Bash Tutorial menu

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

bash
greet() {
    echo "Welcome to Workownix!"
}

greet
greet
Output
Welcome 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

bash
bill() {
    local item=$1
    local price=$2
    local qty=$3
    echo "$qty x $item = Rs $((price * qty))"
}

bill "Samosa" 40 5
bill "Chai" 60 2
Output
5 x Samosa = Rs 200
2 x Chai = Rs 120
VariableHolds
$1, $2, ...The first, second, ... argument
$#The number of arguments
$@All the arguments
$0The 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

bash
name="Ali"

change() {
    local name="Sara"
    echo "Inside: $name"
}

change
echo "Outside: $name"
Output
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

bash
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: $?"
Output
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

bash
#!/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"
done

Run it with two names:

Example

bash
bash welcome.sh Ayesha Bilal
Output
You 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

bash
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.txt

If 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?

Learn Bash with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp