bash: variable outside function scope
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.
Maybe you're confusing bash
with php
. Just remove the $
, the _her
part, and the space:
global_var=$(<bla value>) # or maybe: global_var='<bla value>'
instead of:
$global_var_her = $(<bla value>)
With that, the error goes away.
On the other hand, check that other guy's answer regard to the pipelines.
And yes, it is possible to define a global variable and it is done the way you're doing it.
Maybe is useful pointing something about this:
$(<bla value>)
If <bla value>
is a command, the sentence is ok, because that't the way to capture the output of a command with Command Substitution
.
If, instead, is a literal value, just remove the $()
leaving just '<bla value>'
(global_var='<bla value>'
). This is the same to do $(echo '<bla value>')
but that would be an unnecessary waste of resources.