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
EasyWrite an order script whose function prints one line of the order from the product and price you pass it.
- Open
order.sh. - Define a function named
linethat takes a product and a price and printsPRODUCT costs PRICE. - Below the function, print
Order forfollowed by the script's first argument. - Then call
line Tea 3andline Cake 5. - Save the file.
Try it: run bash order.sh Mia. It prints:
Order for Mia
Tea costs 3
Cake costs 5Then 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground