Bash: declare in depth: Part 4: the oddballs
October 18, 2021•241 words
We've covered almost all of declare's options, but there are two that stand out for being of questionable usefulness: -l
and -u
.
These flags change the case of a variable to lowercase (-l
) and uppercase (-u
) respectively when they are assigned.
In total, I counted three ways for changing casing in Bash:
declare
with-u
or-l
- parameter expansion with
^^
and,,
:${to_upper^^}
and${to_lower,,}
- using an
@
parameter during expansion:${to_upper@U}
and{to_lower@L}
Interaction with namerefs
So how does declare -u
work together with namerefs?
Does it upcase the name of the variable referred to by the nameref?
Does it upcase the assigned value?
Let's find out!
var=1
VAR=2
declare -nu ref=var
ref=3
printf "var=%d, VAR=%d\n" "$var" "$VAR"
# prints var=1 VAR=3
Applied to a nameref, the name of the variable referred to is changed to uppercase.
Application: metaprogramming and enforcing naming conventions
The only application of this that I can think of is enforcing naming conventions of variables when metaprogramming, e.g. global variables should always be in uppercase.
Here's defconst
, a function which defines a global variable, whose value cannot be changed and whose name is always going to be in uppercase.
defconst() {
local -nu ref="$1"
ref="$2"
readonly "${!ref}"
printf "%s" "${!ref}" # the name the reference points to
}
defconst pi 3.14 # prints PI
printf "PI=%s\n" "$PI" # prints 3.14
PI=bar # error: PI: readonly variable