7.7. ArithmeticThe let command allows you to perform arithmetic (Figure 7-15). Figure 7-15. Description of the let shell command.
Here are some examples:
$ let x = 2 + 2 ...expression contains spaces. ksh: =: syntax error ...no spaces or tabs allowed! $ let x=2+2 ...OK. $ echo $x 4 $ let y=x*4 ...don't place $ before variables. $ echo $y 16 $ let x=2#100+2#100 ...add two numbers in base 2. $ echo $x 8 ...number is displayed in base 10. $ _ 7.7.1. Preventing Metacharacter InterpretationUnfortunately, the shell interprets several of the standard operators, such as <, >, and *, as metacharacters, so they must be quoted or preceded by a backslash ( \ ) to inhibit their special meaning. To avoid this inconvenience, there is an equivalent form of let that automatically treats all of the tokens as if they were surrounded by double quotes, and allows you to use spaces around tokens. The token sequence:
(( list )) is equivalent to:
let " list " Note that double quotes do not prevent the expansion of variables. I personally always use the ((..)) syntax instead of let . Here's an example:
$ (( x = 4 )) ...spaces are OK. $ (( y = x * 4 )) $ echo $y 16 $ _ 7.7.2. Testing ValuesArithmetic values may be used by decision-making control structures, such as an if statement:
$ (( x = 4 )) ...assign x to 4. $ if (( x > 0 )) ...OK to use in a control structure. > then > echo x is positive > fi x is positive ...output from control structure. $ _ For simple arithmetic tests, I recommend using ((..)) instead of test expressions. |
7.8. Tilde SubstitutionAny token of the form ~ name is subject to tilde substitution . The shell checks the password file to see if name is a valid user name, and if it is, replaces the ~ name sequence with the full pathname of the user's home directory. If it isn't, the ~ name sequence is left unchanged. Tilde substitution occurs after aliases are processed . Figure 7-16 is a table of the tilde substitutions, including the special cases ~+ and ~-. Figure 7-16. Tilde substitutions in the Korn shell.
The predefined local variables PWD and OLDPWD are described later in this chapter. Here are some examples of tilde substitution:
$ pwd /home/glass ...current working directory. $ echo ~ /home/glass ...my home directory. $ cd / ...change to root directory. $ echo ~+ / ...current working directory. $ echo ~- /home/glass ...previous working directory. $ echo ~dcox /home/dcox ...another user's home directory. $ _ |