Home » Articles » Korn Shell – Variables Quick Reference

Korn Shell – Variables Quick Reference

Korn Shell – Variables Quick Reference

Typeset type and attribute options

-A Create an associative array.
-En Represent the variable internally as a double-precision floating-point number; improves the efficiency of floating-point arithmetic. If n is given, it is the number of significant figures to use in output. Large numbers print in scientific notation: [-]d.ddde±dd. Smaller numbers print in regular notation: [-]ddd.ddd.
-Fn Represent the variable internally as a double-precision floating-point number; improves the efficiency of floating-point arithmetic. If n is given, it is the number of decimal places to use in output. All values print in regular notation: [-]ddd.ddd.
-H On non-Unix systems, Unix-style filenames are converted into the format appropriate for the local system.
-in Represent the variable internally as an integer; improves the efficiency of integer arithmetic. If n is given, it is the base used for output. The default base is 10.
-n Create a nameref variable (see Chapter 4).
-p When used by itself, prints typeset statements that describe the attributes of each of the shell’s variables that have attributes set. With additional options, only prints those variables that have the corresponding attribute set. Intended for dumping the shell’s state into a file that can later be sourced by a different shell to recreate the original shell’s state.
-r Make the variable read-only: forbid assignment to it and disallow it from being unset. The built-in command readonly does the same thing, but readonly cannot be used for local variables.
-t “Tags” the variable. The list of tagged variables is available from typeset +t. This option is obsolete.
-uin Represent the variable internally as an unsigned integer. This is discussed further in Appendix B. If n is given, it is the base used for output. The default base is 10.[88]
-x This does the same thing as the export command, but export cannot be used for local variables.
-f Refer to function names only; see Section 6.5.4, later in this chapter.

[88] This feature is only in ksh93m and newer.

The -i option is the most useful. You can put it in a script when you are done writing and debugging it to make arithmetic run a bit faster, though the speedup will be apparent only if your script does a lot of arithmetic. The more readable integer is a built-in alias for typeset -i, so that integer x=5 is the same as typeset -i x=5. Similarly, the word float is a predefined alias for typeset -E.[89]

[89] C, C++, and Java programmers may find the choice of the word “float” to be suprising, since internally the shell uses double-precision floating point. We theorize that the name “float” was chosen since its meaning is more obvious to the nonprogrammer than the word “double.”

The -r option is useful for setting up “constants” in shell scripts; constants are like variables except that you can’t change their values once they have been initialized. Constants allow you to give names to values even if you don’t want them changed; it is considered good programming practice to use named constants in large programs.

The solution to Task 6-3 contains a good candidate for typeset -r: the variable numcols, which specifies the number of columns in the output. Since numcols is an integer, we could also use the -i option, i.e., replace let numcols=5 with typeset -ri numcols=5. If we were to try assigning another value to numcols, the shell would respond with the error message ksh: numcols: is read only.

These options are also useful without arguments, i.e., to see which variables exist that have those options turned on.

Korn Shell – Variables Expansion

Table 3.5. Variable Expansion Formats

${#variable} length of variable
${variable:–word} value of variable if set and not null, else print word
${variable:= word} value of variable if set and not null, else variable is set to word, then expanded
${variable:+word} value of word if variable is set and not null, else nothing is substituted
${variable:?} value of variable if set and not null, else print ‘variable: parameter null or not set
${variable:?word} value of variable if set and not null, else print value of word and exit
${variable #pattern} value of variable without the smallest beginning portion that matchespattern
${variable ##pattern} value of variable without the largest beginning portion that matchespattern
${variable%pattern} value of variable without the smallest ending portion that matchespattern
${variable%%pattern} value of variable without the largest ending portion that matchespattern
${variable//pattern1/pattern2} replace all occurrences of pattern1 with pattern2 in variable

Variable Pattern Expansion

${variable#pattern}, ${variable##pattern}

This is expanded to the value of variable with the smallest (#) or largest (##) part of the left matched bypattern deleted. What these expansion formats allow you to do is manipulate substrings. To demonstrate the basic functionality, X is set to a string that contains a recurring pattern: abcabcabc.

$ X=abcabcabc

When expanded to return the substring that deletes the smallest left pattern abc, we get abcabc:

$ print ${X#abc*} 
   abcabc

while the substring that deletes the largest left pattern abc is abcabcabc, or the entire string:

$ print ${X##abc*} 
   
   $

${variable%pattern}, ${variable%%pattern}

This is expanded to the value of variable with the smallest (%) or largest (%%) part of the right matched by pattern deleted. This is the same as the parameter expansion format from the previous section, except that patterns are matched from the right instead of left side. It could also be used to display file names without their .suffixes:

$ X=file.Z 
   $ print ${X%.*} 
   file

Here, any trailing digits are stripped:

$ X=chap1 
   $ print ${X%%[0—9]*} 
   chap 
   $ X=chap999 
   $ print ${X%%[0—9]*} 
   chap

The pattern in this command causes it to act like the Unix dirname command. Everything except the last directory is returned if variable X is set to a full pathname.

$ X=/usr/spool/cron 
   $ print ${X%/*} 
   /usr/spool

${variable//pattern1/pattern2}, ${variable/pattern1/pattern2},
${variable#pattern1/pattern2}, ${variable/%pattern1/pattern2}

The Korn shell supports four search and replace operations on variables. This example changes all occurrences of abc in X to xyz:

$ X=abcabcabc 
   $ print ${X//abc/xyz} 
   xyzxyzxyz

while this one only changes the first occurrence of abc in X to xyz:

$ X=abcabcabc 
   $ print ${X/abc/xyz} 
   xyzabcabc

 

${variable:start}, ${variable:start:length}

This format returns a substring. The first returns variable from position start to end, while the second returns length characters from variable from character position start to end. For example, this returns the first 3 characters of X:

$ X=abcdefghij 
   $ print {$X:0:3} 
   abc

while this example returns the value of X starting at character position 5:

$ X=abcdefghij 
   $ print {$X:5} 
   fghij

See Table 3.6 for detailed explanation of the other formats.

Table 3.6. More Variable Expansion Formats

${variable//pattern1/pattern2} replace all occurrences of pattern1 with pattern2 in variable
${variable/pattern1/pattern2} replace first occurrence of pattern1 with pattern2 in variable
${variable/#pattern1/pattern2} replace first occurrence of pattern1 with pattern2 in variable ifvariable begins with pattern1
${variable/%pattern1/pattern2} replace last occurrence of pattern1 with pattern2 in variable ifvariable ends with pattern1
${variable:start} return variable from character position start to end
${variable:start:length} return length characters from variable from character position startto end

 

Array Variable Assignments and Declarations

Arrays can be assigned values by using normal variable assignment statements, the set –A command, or the typeset command:

variable[0]=value variable[1]=value. . . variable[n]=value

or

set –A variable value0 value1 . . . valuen

or

typeset variable[0]=value variable[1]=value. . . \ 
   variable[n]=value

The only difference between the formats is that with the set command format, the values are assigned to the array variable sequentially starting from element zero. In the other formats, the array elements can be assigned values in any order. This example assigns the weekday names to the array variableDAY using normal variable assignment format:

 

Compound Variables

The Korn shell also supports compound variables, which are similar to structures or records in other languages, that is a meta-datatype which is a group of related values, each of which can have a different data type. The syntax for declaring compund variables is:

compound_variable=(
   [datatype] field1[=value] 
   . . . 
   [datatype] fieldn[=value] 
   )

For example, we can use a compound variable to manage employee information:

$ employee=(
   typeset name=Allenby 
   integer id=1243 
   float salary=9000.50 
   )

The syntax to display the value of a compound variable field is:

${compound_variable.field}

Here we access the employee compound variable:

$ print $employee 
   ( typeset -E salary=9000.5 name=Allenby typeset -i 
   id=1243 ) 
   $ print ${employee.name} 
   Allenby

Leave a Reply