A
A
Alexey Babiev2020-06-16 09:29:19
bash
Alexey Babiev, 2020-06-16 09:29:19

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

There is a change_var function in the script that should change the global variable.
If you just call the function, as it is done in print_var_in , then everything works correctly
But if you wrap it in $(), as in print_var_out , then the global variable will not change
How to get around without using files?

Conclusion:
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

2 answer(s)
L
Lynn "Coffee Man", 2020-06-16
@axsmak

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"

Conclusion:
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

S
Saboteur, 2020-06-16
@saboteur_kiev

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 question

Ask a Question

731 491 924 answers to any question