Bash Iterate Array Examples
Functions in Bash shell scripts allow you to group a set of commands together and call them from multiple places in your script. Here are some examples of how to define and call Bash shell script functions:
- Define a function that prints a message to the console:
function my_function { echo "Hello, World!" }You can then call the
my_functionfunction by typing:my_functionThis will print "Hello, World!" to the console.
- Define a function that takes arguments and performs a calculation:
function calculate { result=$(($1 + $2)) echo "The result is: $result" }You can then call the
calculatefunction and pass two arguments by typing:calculate 10 20This will print "The result is: 30" to the console.
- Define a function that returns a value:
function get_greeting { echo "Hello, $1!" }You can then call the
get_greetingfunction and store the result in a variable by typing:greeting=$(get_greeting "John") echo $greetingThis will print "Hello, John!" to the console.
- Define a function that uses a local variable:
function local_variable { local my_var="This is a local variable" echo $my_var }You can then call the
local_variablefunction by typing:local_variableThis will print "This is a local variable" to the console.
