Search code examples
bash

bash: variable outside function scope


Is there a possible way to initialize a global variable in bash and assign it a value in a function, then use it out side the function scope?

Function example:

globla_var=""

_DBINFO()
{
  curl  -su $AUTH https://<balla bla >/databases | jq -c 'map(select(.plan.name != "Sandbox")) | .[] | {id, name}'| \
  while  read db
  do
    idb=$(echo "$db" | jq -r '.id')
    name=$(echo "$db" | jq -r '.name')
    if [[ $name = '<bla>' ]]; then
        $global_var_her = $(<bla value>)
     fi
  done
}

then use it outside the function:

 echo $global_var

the result

   $0: line 16: =<bla bla>: command not found

I tried using declare:

declare -r global_var

same results


Solution

  • Yes you can, but you have to be careful about subshells that limit scope in unexpected ways. Piping to a while read loop like you are doing is a common pitfall.

    Instead of piping to a while read loop, use redirection and process substitution:

    _DBINFO()
    {     
      while read db
      do
        idb=$(echo "$db" | jq -r '.id')
        name=$(echo "$db" | jq -r '.name')
        if [[ $name = '<bla>' ]]; then
            global_var=value
         fi
      done  <  <(curl  -su "$AUTH" "https://$host/databases" |
                   jq -c 'map(select(.plan.name != "Sandbox")) | .[] | {id, name}')
    }
    
    AUTH="user:password"
    host="example.com"
    _DBINFO
    echo "The global variable is $global_var"
    

    You also need to make sure your assignment is syntactically valid. $var = value is not a valid bash assignment, while var=value is. shellcheck can point out many things like that.