Languages
[Edit]
EN

Bash - return values from functions

0 points
Created by:
Zeeshan-Peel
850

This article will show you how to return values from functions in Bash.

Practical examples

1. By setting the result to a global variable

#!/bin/bash

my_function() {
    result="sample value"
}

my_function
echo $result

Output: 

sample value

Note: 

Remember that using global variables is not a safe solution, especially when you are creating a large project.

2. Better solution - use local variables in your function

#!/bin/bash

my_function() {
    local local_result="sample value"
    echo "$local_result"
}

result=$(my_function)
echo $result

Output: 

sample value

 Note: 

`my_funciton` is an alternative notation to $(my_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.

Bash

Bash - return values from functions
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