Table of Contents
Using Substitution Syntax
Use substitution syntax represented by $(...)
to return string from function in Bash.
1 2 3 4 5 6 7 |
function return_string(){ echo "Welcome to Java2Blog" } str=$(return_string) echo "$str" |
1 2 3 |
Welcome to Java2Blog |
You can use local variable as well if you want as below:
1 2 3 4 5 6 7 8 |
function return_string(){ local local_str_var="Java2Blog" echo "Welcome to $local_str_var" } str=$(return_string) echo "$str" |
1 2 3 |
Welcome to Java2Blog |
In this example, the return_string()
function initialized a local variable named local_str_var
with the "Java2Blog"
value. Then, we used an echo
command to print the value of the local_str_var
with a custom text.
Outside the function, we used substitution syntax ($(...)
) to capture the output of the return_string()
function. In the above example, the retrun_string()
output was the output of the echo
command from the function.
We stored the captured output in an str
variable, which we used with another echo
to display on the Bash console.
If you don’t need to store the string for further processing, you can omit substitution syntax; see the following example.
1 2 3 4 5 6 7 |
function return_string(){ local local_str_var="Java2Blog" echo "Welcome to $local_str_var" } return_string |
1 2 3 |
Welcome to Java2Blog |
Using Global Variable
Use a global variable to return string from function in Bash.
1 2 3 4 5 6 7 8 |
global_str_var="" function return_string(){ global_str_var="Java2Blog" } return_string echo "$global_str_var" |
1 2 3 |
Java2Blog |
We initialized the global_str_var
variable with an empty string. Then, inside the return_string()
function, we modified the value of the global_str_var
variable from an empty string to "Java2Blog"
. We then accessed the global_str_var
variable’s modified value after invoking the function using return_string
.
Using Here-String Operator
Use the here-string operator represented by <<<
to return a string value from a function, which was passed to a command within the function.
1 2 3 4 5 6 7 8 |
function return_string(){ local local_str_var="Java2Blog" cat <<< "Welcome to $local_str_var" } str=$(return_string) echo "$str" |
1 2 3 |
Welcome to Java2Blog |
This example resembles the one where we used substitution syntax, but this time, instead of echoing, we returned the string from the function, which was passed to the cat
command using the here-string (<<<
) operator.
Using Here-Document Operator
Use the here-document operator to return string from function in Bash.
1 2 3 4 5 6 7 8 9 |
function return_string(){ cat << EOF Java2Blog EOF } str=$(return_string) echo "$str" |
1 2 3 |
Java2Blog |
Here, we used the here-document operator that you can learn in our previously published Echo multiple lines in Bash.
That’s all about Bash return String from function.