Reputation: 43494
I'm working on a shell script and I have some lines of code that are duplicated (copy pasted, let's say).
I want those lines to be in a function. What is the proper syntax to use?
And what changes shoud I do in order for those functions to receive parameters?
Here goes an example.
I need to turn this:
amount=1
echo "The value is $amount"
amount=2
echo "The value is $amount"
Into something like this:
function display_value($amount) {
echo "The value is $amount"
}
amount=1
display_value($amount)
amount=2
display_value($amount)
It is just an example, but I think it's clear enough.
Thanks in advance.
Upvotes: 13
Views: 30086
Reputation: 463
In a shell script, functions can accept any amount of input parameters. $1 stands for the 1st input parameter, $2 the second and so on. $# returns the number of parameters received by the function and $@ return all parameters in order and separated by spaces.
For example:
#!/bin/sh
function a() {
echo $1
echo $2
echo $3
echo $#
echo $@
}
a "m" "j" "k"
will return
m
j
k
3
m j k
Upvotes: 19
Reputation: 19290
function display_value() {
echo "The value is $1"
}
amount=1
display_value $amount
amount=2
display_value $amount
Upvotes: 22