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 (return
works only with numbers), - use
my_variable="$(my_function)"
to call the function, and retrieve the string.
Practical example:
xxxxxxxxxx
1
2
3
function my_function()
4
{
5
local my_variable='Some text inside ...'
6
echo "$my_variable"
7
}
8
9
my_variable="$(my_function)"
10
echo "$my_variable"
You can use the global variables approach, which requires keeping some order in the source code.
xxxxxxxxxx
1
2
3
function my_function()
4
{
5
my_variable='Some text inside ...'
6
}
7
8
my_function
9
echo "$my_variable"
or:
xxxxxxxxxx
1
2
3
function_result=''; # should be used only to store last function call result
4
5
function my_function()
6
{
7
local my_variable='Some text inside ...'
8
9
function_result="$my_variable"
10
return 0 # 0 - means success
11
# 1, 2, 3, etc. - means error (some error code)
12
}
13
14
if my_function
15
then
16
echo "$function_result"
17
fi