Code:
#test.sh
test_func(){
var1="$1"
var2="$1"
echo "var1 before typeset: $var1"
echo "var2 before typeset: $var2"
typeset -l var1="$1"
typeset -l var2
echo "var1 after typeset: $var1"
echo "var2 after typeset: $var2"
}
test_func "$1"
var1="$1"
var2="$1"
echo "var1 before typeset: $var1"
echo "var2 before typeset: $var2"
typeset -l var1=$1
typeset -l var2
echo "var1 after typeset: $var1"
echo "var2 after typeset: $var2"
output using bash with input SAMPLE_INPUT:
var1 before typeset: SAMPLE_INPUT
var2 before typeset: SAMPLE_INPUT
var1 after typeset: sample_input
var2 after typeset:
var1 before typeset: SAMPLE_INPUT
var2 before typeset: SAMPLE_INPUT
var1 after typeset: sample_input
var2 after typeset: SAMPLE_INPUT
output using ksh:
var1 before typeset: SAMPLE_INPUT
var2 before typeset: SAMPLE_INPUT
var1 after typeset: sample_input
var2 after typeset: sample_input
var1 before typeset: sample_input
var2 before typeset: sample_input
var1 after typeset: sample_input
var2 after typeset: sample_input
I dont understand why bash clobbers var2 in a function and why ksh changing the variable inside a function affects the value of it outside the function when re grabbing the value from $1. I assume this has something to do with their implementation of local vs global variables.
my desired output would be the same on bash and ksh and inside/outside of a function:
var before typeset: SAMPLE_INPUT
var after typeset: sample_input
used out of function:
var before typeset: SAMPLE_INPUT
var after typeset: sample_input
In bash,
typesetis an alias fordeclare, which makes variables local when invoked inside a function unless the argument-gis added.In ksh,
typesethas different behavior depending on how you defined your function: Withtest_func() { ... }variables created withtypesetare global; withfunction test_func { ... }they're local. Because you're using thetest_func() {syntax, in your ksh code,typesetrefers to the preexisting global variable instead of creating a local; so the original value is retained.If you want identical behavior, you need to move
typesetoutside of the function, or add-gwhen the shell is bash; the latter can be done with a parameter expansion that emits-gonly whenBASH_VERSIONis set, as below:...properly emits:
...even on bash.
As for the empty value, you get that even on ksh if you change your function declaration syntax to make
typesetcreate locals by default:...emits,
Result is: <>when run in ksh.