Bash Function
A function is a named block of commands. Define it once, then call it by name as often as you like.
Arguments are read with $1, $2 and so on. Use echo to send back a value, and return to set the exit status.
Define and call a function
Save this as greet.sh:
#!/bin/bash
greet() {
echo "Hello, $1!"
}
greet "Tove"
greet "Linus"
Run it:
./greet.sh
Hello, Tove!
Hello, Linus!
Get a value back
Save this as add.sh:
#!/bin/bash
add() {
echo $(( $1 + $2 ))
}
sum=$(add 3 4)
echo "The sum is $sum"
Run it:
./add.sh
The sum is 7