Edit global var and return it (or static var)

Viewed 74

I need to be able to modify a string of a global (or static function) variable and in the meantime return it.
I can't find what I'm looking for online...


To make the question clearer, in Python3 will be something like this:

def get_static_variable():
  if 'val' not in get_static_variable.__dict__:
    # Some other code...
    print('Some other code test') # Prints one time
    get_static_variable.val = "Hello World!"
  return get_static_variable.val

print('FUN: ' + get_static_variable())
print('FUN: ' + get_static_variable())

And this works correctly...

Some other code test
FUN: Hello World!
FUN: Hello World!

In bash I tried something like this:

#!/usr/bin/env bash

GLOBAL_VAR=""

function get_global_var(){
    if [ -z "$GLOBAL_VAR" ]; then
        # Some other code...
        GLOBAL_VAR="Hello World!"
    fi
    echo $GLOBAL_VAR
}

echo "FUN: $(get_global_var)"
echo "VAR: ${GLOBAL_VAR}"

But as you can imagine, it doesn't work...

FUN: Hello World!
VAR: *empty*
2 Answers

Variables are always global, no matter where you first assign them a value, unless explicitly declared as local. I believe the issue here is that $(get_global_var) spawns a sub-shell, thus the value "Hello World!" is only assigned in this sub-shell and never in the calling shell.

This will work:

GLOBAL_VAR=""

function get_global_var(){
    [ -z "$GLOBAL_VAR" ] && GLOBAL_VAR="Hello World!"
    echo $GLOBAL_VAR
}

get_global_var
echo "VAR: ${GLOBAL_VAR}"

This will also work of course, and I think it should be your preferred choice (don't rely on global assignments, just on returned values):

# as the name says, only "get" the value, don't "set" it
function get_global_var(){
    if [ -z "$GLOBAL_VAR" ]; then
      echo "Hello World!"
    else
      echo "whatever else"
    fi
}

GLOBAL_VAR=$(get_global_var)
echo "VAR: ${GLOBAL_VAR}"

Even better (I fiercely dislike global variables unless strictly necessary), make it fully functional:

function get_var() {
    if [ -z "$1" ]; then
      echo "Hello World!"
    else
      echo "whatever else"
    fi
}

GLOBAL_VAR=$(get_var ${GLOBAL_VAR})
echo "VAR: ${GLOBAL_VAR}"

The most simple solution to achieve what you want to do is by using variable substitution,

GLOBAL_VAR=""

echo "FUN: ${GLOBAL_VAR:="Hello World!"}"
echo "VAR: $GLOBAL_VAR"

Here, if GLOBAL_VAR is empty(null) then the value in double quotes is assigned to that variable.

Related