Background
Playing around with Bash and just really wrestling on how to tokenize a string and return its parts.
Honestly, it is much simpler than that.
It can only have two whole pieces; I cheated and made sure of that while curating the dataset.
Options
Here are the options available for returning data from a function
- Use echo <data> to return the intended data
- Use name reference
Echo Data
Outline
- Calling Function
- Invoke child function
- Syntax
-
variable=$(function)
-
- Sample
-
usernameRet_=$(getUserInput)
-
- Syntax
- Invoke child function
- Called Function
- Return value using echo
- Syntax
-
echo <variable>
-
- Sample
-
echo "$username_"
-
- Syntax
- Return value using echo
Code
#!/bin/bash function getUserInput() { #declare variables local username_="" #read data read username_ #return variables echo "$username_" } #greetings echo "hello, who am I talking to..." #get data usernameRet_=$(getUserInput) echo "The name entered is $usernameRet_"
Pass by Name Reference
Outline
- Calling Function
- Invoke child function
- Pass along reference
- Notice that variable is noted without $
- Pass along reference
- Invoke child function
- Called Function
- Declare Variable and Set equal to the positioned argument
- Syntax
-
declare -n [variable]=${n}
-
- Sample
-
declare -n usernameref_=$1
-
- Syntax
- In function, set a reference variable to the new value
- Syntax
-
[variable]=[value]
-
- Sample
-
usernameref_="samuel"
-
- Syntax
- Declare Variable and Set equal to the positioned argument
Code
#!/bin/bash function getUserInput() { #declare a name reference #The name reference should reference the first parameter declare -n usernameref_=$1 #prompt user for his/her name echo Hello, who am I talking to? #accept name and place in name reference read usernameref_ } # Hello World Program in Bash Shell username='' #invoke function #pass variable by reference getUserInput username #echo data echo "Hello $username"
Source Code Control
GitHub
Gist
#!/bin/bash | |
function getUserInput() | |
{ | |
#declare variables | |
local username_="" | |
#read data | |
read username_ | |
#return variables | |
echo "$username_" | |
} | |
#greetings | |
echo "hello, who am I talking to…" | |
#get data | |
usernameRet_=$(getUserInput) | |
echo "The name entered is $usernameRet_" |
#!/bin/bash | |
function getUserInput() | |
{ | |
#declare a name reference | |
#The name reference should reference the first parameter | |
declare -n usernameref_=$1 | |
#prompt user for his/her name | |
echo Hello, who am I talking to? | |
#accept name and place in name reference | |
read usernameref_ | |
} | |
# Hello World Program in Bash Shell | |
username='' | |
getUserInput username | |
echo "Hello $username" |