Functions with arguments
suggest changeIn helloJohn.sh
:
#!/bin/bash
greet() {
local name="$1"
echo "Hello, $name"
}
greet "John Doe"
# running above script
$ bash helloJohn.sh
Hello, John Doe
- If you don’t modify the argument in any way, there is no need to copy it to a
local
variable - simplyecho "Hello, $1"
. - You can use
$1
,$2
,$3
and so on to access the arguments inside the function.
Note: for arguments more than 9 $10 won’t work (bash will read it as **$1**0), you need to do `${10},${11}` and so on.
$@
refers to all arguments of a function:
#!/bin/bash foo() { echo “$@” }
foo 1 2 3 # output => 1 2 3
>**Note:** You should practically always use double quotes around `"$@"`, like here.
Omitting the quotes will cause the shell to expand wildcards (even when the user specifically quoted them in order to avoid that) and generally introduce unwelcome behavior and potentially even security problems.
foo “string with spaces;” ‘$HOME’ “*”
output => string with spaces; $HOME *
- for default arguments use
${1:-default_val}
. Eg:
#!/bin/bash
foo() {
local val=${1:-25}
echo "$val"
}
foo # output => 25 foo 30 # output => 30
5. to require an argument use `${var:?error message}`
foo() {
local val=${1:?Must provide an argument}
echo "$val"
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents