How to Use Korn Shell (ksh) let statement
The Korn Shell let Statement
The let statement is an alternative to the ((…)) statement. Type the arithmetic formula with no spaces unless the formula is enclosed in double-quote (") characters. Assign a numeric value, using the formula syntax, without using the let statement. It’s common to use the Korn shell ((…)) syntax instead of the let statement:
$ let a=1 $ let b=3 $ let c=4 $ echo $a 1 $ let "a = a + 1" $ echo $a 2 $ let a=b+c $ echo $a 7 $ ((a = b + c)) $ echo $a 7 $ a=b+c $ echo $a b+c
The following script:
- Assigns the value 99 to the variable y.
- Computes the cube of the number entered, the quotient of the number entered divided by 4, and the remainder of the number entered divided by 4.
- Prints the results with an appropriate message.
- Computes the number input using the quotient, the divisor 4, and the remainder.
- The result is multiplied by 2 and saved in the variable z.
- A message showing the z value prints.
$ cat math.ksh #!/bin/ksh # Script name: math.ksh # This script finds the cube of a number, and the # quotient and remainder of the number divided by 4. y=99 (( cube = y * y * y )) (( quotient = y / 4 )) (( rmdr = y % 4 )) print "The cube of $y is $cube." print "The quotient of $y divided by 4 is $quotient." print "The remainder of $y divided by 4 is $rmdr." # Notice the use of parenthesis to # control the order of evaluating. (( z = 2 * (quotient * 4 + rmdr) )) print "Two times $y is $z." $ ./math.ksh The cube of 99 is 970299. The quotient of 99 divided by 4 is 24. The remainder of 99 divided by 4 is 3. Two times 99 is 198.