In helloJohn.sh
:
#!/bin/bash
greet() {
local name="$1"
echo "Hello, $name"
}
greet "John Doe"
# running above script
$ bash helloJohn.sh
Hello, John Doe
local
variable - simply echo "Hello, $1"
.$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 $10), 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’ “*”
${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}`