ennuikiller ennuikiller - 2 months ago 9
Bash Question

Is there any difference between using typeset in ksh to simply setting a variable?

Are the following 2 lines completely equivalent? If not what's the difference? I've seen plenty of shell scripts utilize number 1 and was just wondering what it gives you compared with number 2.


  1. typeset TARGET="${XMS_HOME}/common/jxb/config/${RUNGROUP}.${ENV}.properties"

  2. TARGET="${XMS_HOME}/common/jxb/config/${RUNGROUP}.${ENV}.properties"


Answer

typeset will create a local variable (one which doesn't "leak"). This is useful in functions but I've also seen it being used at the top level of a shell script.

a=0
function x {
    typeset a=1
}
x
echo $a
function y {
    a=2
}
y
echo $a

will print

0
2

You can also use typeset to create arrays and integers.

[EDIT] Added function keyword because some shells require it. Remove it if it offends your shell but it should work with most versions.