EN
Bash - return string from function
5
points
In this short article, we would like to show how to return string / text from a function in Bash.
Quick solution:
- use
echo "$my_variable"to print a string inside a function (returnworks only with numbers), - use
my_variable="$(my_function)"to call the function, and retrieve the string.
Practical example:
#!/bin/bash
function my_function()
{
local my_variable='Some text inside ...'
echo "$my_variable"
}
my_variable="$(my_function)"
echo "$my_variable"
Alternative solution
You can use the global variables approach, which requires keeping some order in the source code.
#!/bin/bash
function my_function()
{
my_variable='Some text inside ...'
}
my_function
echo "$my_variable"
or:
#!/bin/bash
function_result=''; # should be used only to store last function call result
function my_function()
{
local my_variable='Some text inside ...'
function_result="$my_variable"
return 0 # 0 - means success
# 1, 2, 3, etc. - means error (some error code)
}
if my_function
then
echo "$function_result"
fi