Bash Bonanza Part 3: Functions

#!/usr/bin/env bash 

# Function definition
function_name() { echo "Hello World!" }
# Function call
function_name
Hello World!
tasty_thing="Pineapples" function_name 'Hello World!' "$tasty_thing"
#!/usr/bin/env bash 
# $1 - greeting
# $2 - message to the world greet_world() { # Note: shift will shift the arguments down, so $2 becomes $1 # This is a personal preference - you don't have to use it local greeting="$1"; shift local message="$1"; shift
echo "$greeting World!"
echo "$message" }
greeting="Aloha"
greet_world "$greeting" 'I ate a large pineapple today!'
Aloha World! I ate a large pineapple today!
response=$(greet_world "$greeting" 'I ate a large pineapple today!') # parse response however you want
# $1 - variable name # $2 - variable value function indirect-string-assignment() {       # INPUT       local variable_name="$1"; shift       local variable_value="$1"; shift 
unset -v "$variable_name" || echo "Invalid identifier:
$variable_name" >&2 printf -v "$variable_name" '%s' "$variable_value" }
#!/usr/bin/env bash 
# INPUT
# $1 - variable name # $2 - variable value function indirect-string-assignment() { local variable_name="$1"; shift local variable_value="$1"; shift unset -v "$variable_name" || echo "Invalid identifier:$variable_name" >&2 printf -v "$variable_name" '%s' "$variable_value" }
# INPUT
# $1 - greeting # $2 - message to the world
# OUTPUT
# $3 - variable name that will hold a greeting from the world # $4 - variable name that will hold a reply to your message from the world greet_world() { # INPUT local greeting="$1"; shift local message="$1"; shift # OUTPUT local return_greeting_variable_name="$1"; shift local return_reply_variable_name="$1"; shift
echo "$greeting World!"
echo "$message"
# create ANOTHER local variable with the same name as the one in main
# indirect-string-assignment will then unset THIS local variable, and set the response value on the next one down, which is the local variable in main # this works because since greet_world was called from main, it actually has access to all of main's local variables local "$return_greeting_variable_name" && indirect-string-assignment "$return_greeting_variable_name" "${greeting}!" local "$return_reply_variable_name" && indirect-string-assignment "$return_reply_variable_name" 'That'"'"'s great!' } main() { local greeting="Aloha" # create local world_greeting and world_reply and pass the variable NAMES to the greet_world function local world_greeting && local world_reply && greet_world "$greeting" 'I ate a large pineapple today!' 'world_greeting' 'world_reply'
echo "$world_greeting"
echo "$world_reply" }
main
Aloha World! I ate a large pineapple today! Aloha! That's great!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store