Skip to content

Instantly share code, notes, and snippets.

@lucasjellema
Last active December 18, 2019 14:50
Show Gist options
  • Save lucasjellema/b2f54d2f427a9dc1767970f2ee472e5b to your computer and use it in GitHub Desktop.
Save lucasjellema/b2f54d2f427a9dc1767970f2ee472e5b to your computer and use it in GitHub Desktop.
Example of how to call a function in a Linux Shell Script - passing in input parameters and receiving the result from the function (in a way that resembles modern programming languages)
# a global variable
WELCOME_ROOT=Hello
# invoke this function with two arguments:
# 1. (FROM_VAR) the name of the greeter
# 2. (TO_VAR) the name of the greetee
# this function returns a welcoming message
get_welcoming_message()
{
FROM_VAR=$1
TO_VAR=$2
# local variable THE_MESSAGE is used while composing the result; it is not accessible from outside the function
local THE_MESSAGE=""
THE_MESSAGE="$WELCOME_ROOT to $TO_VAR from $FROM_VAR"
THE_MESSAGE="$THE_MESSAGE !!!"
# this line provides the output from this function; this output can be captured in a variable by the caller using VAR=$(function param1)
echo "$THE_MESSAGE"
}
GUEST=Joe
# invoke function get_welcoming_message with two arguments (Jack and $GUEST) and capture the result in variable WELCOME_MESSAGE
WELCOME_MESSAGE=$(get_welcoming_message "Jack" $GUEST)
echo "message= $WELCOME_MESSAGE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment