Created
October 10, 2018 10:51
-
-
Save taikedz/055a24a3922d6fc99a0d75baa42dc809 to your computer and use it in GitHub Desktop.
Some advanced variable manipulation investigation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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[@]}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output from above script