Answer the question
In order to leave comments, you need to log in
How to use global variables of an executable function in $()?
#!/bin/bash
export GLOBAL_VAR=1
function change_var {
GLOBAL_VAR=$(($GLOBAL_VAR*2))
}
function print_var_out {
echo "[out] Before: $GLOBAL_VAR"
a=$(change_var)
echo "[out] After: $GLOBAL_VAR"
}
function print_var_in {
echo "[in] Before: $GLOBAL_VAR"
change_var
echo "[in] After: $GLOBAL_VAR"
}
print_var_out
print_var_in
bin [master●●] % ./test.sh
[out] Before: 1
[out] After: 1
[in] Before: 1
[in] After: 2
Answer the question
In order to leave comments, you need to log in
Based on the answer to StackOverflow
The function updates the variable last_call
(no longer global), the result assigns the variable the name of which was passed to it in the parameters, and the exit code works as usual.
#!/bin/bash
last_call=never
function f {
local -n res=$1
printf -v last_call '%(%x %X)T'
res=$(($res * 2))
}
result=1
echo "Before: $last_call $result"
f result
echo "Return code: $?"
echo "After: $last_call $result"
sleep 1
f result
echo "Return code: $?"
echo "After: $last_call $result"
Before: never 1
Return code: 0
After: 06/16/2020 02:48:23 PM 2
Return code: 0
After: 06/16/2020 02:48:24 PM 4
a=$(change_var)
You are not just executing a function here, but you want to assign a variable, a function output.
But your function outputs NOTHING.
Additionally, here you are executing code that will run in a subprocess. And changing the variable will be done in a subprocess. Then the subprocess is closed, and in the main process the variable did not change.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question