Skip to content

Instantly share code, notes, and snippets.

@taikedz
Created October 10, 2018 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taikedz/055a24a3922d6fc99a0d75baa42dc809 to your computer and use it in GitHub Desktop.
Save taikedz/055a24a3922d6fc99a0d75baa42dc809 to your computer and use it in GitHub Desktop.
Some advanced variable manipulation investigation
#!/bin/bash
printarr() {
echo "$msg"
local x
for x in "$@"; do
echo " $x"
done
}
add-a() {
#By using `-n` we can access variables from any context
#we can essentially reach out by name - perhaps no need for context sourcing
local -n myarr="$1"
myarr+=(a)
}
change-s() {
# even works on strings
local -n mystr="$1"
mystr=newvalue
}
func() {
local f # if 'f' is changed by change-s before func is called, `local` or `declare` will cancel out the change
echo " f :: $f"
}
ro () {
readonly ro_mesg=hello
echo " ro >> $ro_mesg"
}
arrdef() {
local basearr=(one two)
msg=before/basearr printarr "${basearr[@]}"
add-a basearr
msg=after/basearr printarr "${basearr[@]}"
add-a mainarr
msg=after/mainarr printarr "${mainarr[@]}"
thisstr=oldvalue
echo "thisstr/before :: $thisstr"
change-s thisstr
echo "thisstr/after :: $thisstr"
# Change a "local" before it is called
change-s f
func
echo "Pre-ro"
change-s ro_mesg
ro
echo "Post-ro change-s"
change-s ro_mesg # bails here
echo "Post-ro ro"
ro
echo "Post re-ro"
}
main() {
mainarr=(alice bob)
arrdef
msg="main/basearr" printarr "${basearr[@]}"
msg="main/mainarr" printarr "${mainarr[@]}"
}
main "$@"
msg=global/basearr printarr "${basearr[@]}"
@taikedz
Copy link
Author

taikedz commented Oct 10, 2018

Output from above script

before/basearr
    one
    two
after/basearr
    one
    two
    a
after/mainarr
    alice
    bob
    a
thisstr/before :: oldvalue
thisstr/after :: newvalue
  f :: 
Pre-ro
  ro >> hello
Post-ro change-s
variables_test.sh: line 21: ro_mesg: readonly variable
global/basearr

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment