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.
To invoke a function, simply use the function name as a command. To pass parameters to the function, add space-separated arguments like other commands. The passed parameters can be accessed inside the function using the standard positional variables i.e. $0, $1, $2, $3, etc.
A bash shell script have parameters. These parameters start from $1 to $9. When we pass arguments into the command line interface, a positional parameter is assigned to these arguments through the shell. The first argument is assigned as $1, second argument is assigned as $2 and so on...
Creating Functions The name of your function is function_name, and that's what you will use to call it from elsewhere in your scripts. The function name must be followed by parentheses, followed by a list of commands enclosed within braces.
Bash Function Arguments To pass arguments to a function, add the parameters after the function call separated by spaces.
function display_value() {
echo "The value is $1"
}
amount=1
display_value $amount
amount=2
display_value $amount
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With