How to assign function output to a variable using bash?

I have a bash function that produces some output:

function scan { echo "output" } 

How to assign this output to a variable?

t. VAR = scan (of course, this will not work - this makes VAR equal to the string "scan")

+50
function variables bash
Nov 27 '09 at 17:36
source share
3 answers
 VAR=$(scan) 

In the same way as for programs.

+82
Nov 27 '09 at 17:37
source share

You can use bash functions in commands / pipelines, because otherwise you would use regular programs. These features are also available for subnets and in transit, Command Substitution:

 VAR=$(scan) 

Is the strighforward method to achieve the desired result in most cases. Below I will talk about special cases.

Saving trailing lines:

One of the (usually useful) side effects of Command Substitution is that it will strip any number of line endings. If you want to keep the trailing newline characters, you can add a dummy character to display the subshell and subsequently split it with the parameter extension.

 function scan2 () { local nl=$'\x0a'; # that just \n echo "output${nl}${nl}" # 2 in the string + 1 by echo } # append a character to the total output. # and strip it with %% parameter expansion. VAR=$(scan2; echo "x"); VAR="${VAR%%x}" echo "${VAR}---" 

prints (3 lines supported):

 output --- 

Use output parameter: avoid subshell (and save newlines)

If what the function is trying to do is "return" the string to a variable, with bash v4.3 and up, you can use what is called nameref . Namerefs allows a function to take the name of one or more output parameters of variables. You can assign things to the nameref variable, and it is as if you have changed the variable that it points to / links.

 function scan3() { local -n outvar=$1 # -n makes it a nameref. local nl=$'\x0a' outvar="output${nl}${nl}" # two total. quotes preserve newlines } VAR="some prior value which will get overwritten" # you pass the name of the variable. VAR will be modified. scan3 VAR # newlines are also preserved. echo "${VAR}===" 

prints:

 output === 

This form has several advantages. Namely, it allows your function to change the caller’s environment without using global variables everywhere.

Note. Using namerefs can significantly improve the performance of your program if your functions depend heavily on the bash built-in functions, as this avoids creating a subshell that is immediately thrown away. This is usually more important for commonly used multi-frequency functions, for example. functions ending with echo "$returnstring"

This is relevant. stack overflow

+7
Oct 08 '16 at 9:40
source share

I think init_js should use declare instead of local!

 function scan3() { declare -n outvar=$1 # -n makes it a nameref. local nl=$'\x0a' outvar="output${nl}${nl}" # two total. quotes preserve newlines } 
0
Apr 30 '17 at 10:23
source share



All Articles