Languages
[Edit]
EN

Bash - return string from function

5 points
Created by:
Khloe-Kaiser
578

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:

#!/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

Alternative titles

  1. Bash - return text from function
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join