Image of Beginning Google Maps API 3
Image of Modern Operating Systems (3rd Edition)
Image of Advanced Programming in the UNIX Environment, Second Edition (Addison-Wesley Professional Computing Series)
Image of Operating System Concepts

Bash and Korn Shell Let Keyword

Recently a colleague of mine recommended using the let keyword in shell scripts to perform arithmetic evaluation. That prompted me to write this post about the let keyword.

Here is what the bash manpage says about the let keyword:

let arg [arg ...]
    Each arg is an arithmetic expression to be evaluated. If the last arg evaluates to 0,
    let returns 1; 0 is returned otherwise.

And here is a simple example of it’s use:

$ a=2
$ b=5
$ let c=$a+$b
$ echo $c
$ let c=$a + $b
$ echo $c

As you can see from the above, you cannot have any spaces in arguments.

Here is what ksh93 says about the let keyword:

$ let --man

  let evaluates each expr in the current shell environment as an arithmetic
  expression using ANSI C syntax. Variables names are shell variables and they
  are recursively evaluated as arithmetic expressions to get numerical values.

  let has been made obsolete by the ((...)) syntax of ksh(1) which does not
  require quoting of the operators to pass them as command arguments

By the way, in case you are unaware of it, Korn Shell 93 keywords have built in manpages which are viewed using the –man option as show above.

Here is how to to write the previous example using modern syntax:

$ a=2
$ b=5
$ c=$((a + b))
$ echo $c

My advise to you – stop using the let. keyword when writing shell scripts. Use the modern syntax. It will make your shell scripts easier to read and understand.

Comments are closed.