Bash Return String from Function

Bash return String from function

Using Substitution Syntax

Use substitution syntax represented by $(...) to return string from function in Bash.

You can use local variable as well if you want as below:

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.

Using Global Variable

Use a global variable to return string from function in Bash.

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.

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.

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.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *