Home > database >  Does declare -u in bash also make variables locally scoped?
Does declare -u in bash also make variables locally scoped?

Time:04-09

I'm mystified by the output of this example script. It seems as if some_other_var is being implicitly declared as local when I declare it as uppercase (declare -u):

#!/bin/bash

function works() {
    some_var="${1}"
    printf "in the function, some_var is ${some_var}\n"
}

function doesnt_work() {
    declare -u some_other_var="${1}"
    printf "in the function, some_other_var is ${some_other_var}\n"
}

works "apple"
printf "got back this value of some_var from the function: ${some_var}\n"

doesnt_work "banana"
printf "got back this value of some_other_var from the function: ${some_other_var}\n"

Output:

in the function, some_var is apple
got back this value of some_var from the function: apple
in the function, some_other_var is BANANA
got back this value of some_other_var from the function: 

declare -u is supposed to make the variable uppercase-only, which it does. But is it supposed to also make a variable locally scoped? I was under the impression that one had to use the 'local' directive to explicitly mark a variable as local, otherwise it was global, but declare -u seems to behave differently.

This is:

GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)

CodePudding user response:

That's a general property of declare: when used in a function, it implies local scope. To use global scope, the -g flag (Bash 4.2 ) has to be used.

See the manual:

When used in a function, declare makes each name local, as with the local command, unless the -g option is used.

  •  Tags:  
  • bash
  • Related