Languages
[Edit]
EN

Bash - run function and put output to string variable

0 points
Created by:
Hiba-Tate
548

In this article, we would like to show you how to run function in string and assign result to variable in Bash.

Practical example

In this example, we create example say_hello() function and run it inside a strings assigning results to the corresponding variables.

#!/bin/bash

function say_hello() {
    echo "Hello $1";
}


# Usage example:

name_1="Tom"
result_1="$(say_hello "$name_1")" # runs say_hello() and puts output into result_1 variable

name_2="Mark"
result_2="$(say_hello "$name_2")" # runs say_hello() and puts output into result_2 variable

echo "name: $string_1   result: $result_1"
echo "name: $string_2   result: $result_2"

 

See also

  1. Bash - run command in string and assign result to variable

Alternative titles

  1. Bash - put function result to string
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