KSH Variable Category
- function variable
- It must be explicitly declared within a function using typeset command.
- It's valid only within the function it is declared.
- script/file variable
- It's defined in a file, and valid in that file.
- script/file variable is not valid in its callee script/file, until it's EXPORT-ed to environment.
- system environment variable
- environment can be shared anywhere.
All function variables, except those explicitly declared locally within the function with the typeset command, are inherited and shared by the calling Korn shell script.
For example:
# Function variable:
# Functions act almost just like external scripts, all variables are SHARED between the same ksh process.
# If a variable is changed inside a function, the variable value is changed after it has left the function.
VARA=AA
VARB=BB
function foo
{
echo "1: VARA=$VARA,VARB=$VARB,VARC=$VARC" # 1: VARA=AA,VARB=BB,VARC=
eval $1=AF # action VARA=AF
VARB=BF
VARC=CF
}
foo VARA
echo "2: VARA=$VARA,VARB=$VARB,VARC=$VARC" # 2: VARA=AF,VARB=BF,VARC=CF
Variable Type
Basically, there is no data type concept inksh (except typeset -i, we will talk later), all values can be treated asstring; and when a numeric value is required , it can be converted dynamicallyas needed.
Variable Set
VAR_NAME1="ABC"
VAR_NAME2=ABC #same as “ABC”
VAR_NAME3="123"
VAR_NAME4=20 # same as “20”, but it can be parsed asnumeric when needed.
VAR_ID1=NAME5
VAR_ID2=NAME6
eval VAR_${VAR_ID1}=true # VAR_NAME5=true, it’s same as “true”
eval VAR_${VAR_ID2}=false # VAR_NAME6=false, it’s same as “false”
VAR_NAME7=${VAR_NAME3} # VAR_NAME7=”123”
eval VAR_NAME8=\$\{VAR_${VAR_ID1}\} # VAR_NAME8=true, the value of VAR_NAME5
Variable Unset
unset VAR_NAME7 # unsetVAR_NAME7
unset VAR_${VAR_ID1} # unset VAR_NAME5
Numeric Variable
let’s talk about “-i” attribute, which isused to declare a variable as numeric type.
typeset -i VAR_INT=12
typeset -i VAR_INT=”12” # has same behavior as “12”, because string“12” was parsed as integer 12.
When a variable is declared as an integer,it can be calculated as:
VAR_INT=VAR_INT+5
Instead of
((VAR_INT=VAR_INT+5))
Variable Attribute(typeset)
typeset -i Parameter is an integer.
typeset -l All upper-case characters are converted to lower-case.
typeset -L Left justify and remove leading blanks from value.
typeset -r The given names are marked readonly and these names cannot be changed by subsequent assignment.
typeset -R Right justify and fill with leading blanks.
typeset -u All lower-case characters are converted to upper-case characters.
typeset -x The given names are marked for automatic export to the environment of subsequently-executed commands.