Menu
CoddyTech

Function Arguments

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 12 of 39.

A function takes arguments the way a script does: you write them after its name when you call it. Inside the function, $1, $2 and $# belong to that call, not to the script. To use one of the script's arguments in a function, pass it in the call.

#!/bin/bash
log() {
  echo "[$1] $2 ($# args)"
}
log INFO "Backup started"
log WARN "Disk at $1%"

Run it as bash backup.sh 91:

[INFO] Backup started (2 args)
[WARN] Disk at 91% (2 args)

In each call, $1 inside log is the level and $# is 2. On the last line, outside the function, $1 is the script's argument 91, which reaches log as part of its second argument. Quote an argument that has spaces, such as "Backup started", so the function gets it as one.

challenge icon

Challenge

Easy

Write an order script whose function prints one line of the order from the product and price you pass it.

  1. Open order.sh.
  2. Define a function named line that takes a product and a price and prints PRODUCT costs PRICE.
  3. Below the function, print Order for followed by the script's first argument.
  4. Then call line Tea 3 and line Cake 5.
  5. Save the file.

Try it: run bash order.sh Mia. It prints:

Order for Mia
Tea costs 3
Cake costs 5

Then run bash order.sh Leo: the first line becomes Order for Leo. The other two lines stay the same, because line reads its own arguments, not the script's.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground