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';
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
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
init_js Oct 08 '16 at 9:40 2016-10-08 09:40
source share