Shell Programming  «Prev  Next»

Different Programming Tools

Choosing the right programming tool for the job

The correct matches are:
  1. ${#variable}: Return the length of the variable (number of characters)
  2. ${variable}: Return the value of the variable (method used to avoid ambiguous variable naming)
  3. $variable: Return the value of the varialbe (standard method of referencing a variable)
  4. ${variable:-response}: Return response if the variable is not set
  5. ${variable:=response}: Return response if the variable is not defined and set the variable equal to response
  6. ${variable:?response}: Return response as an error messge if the variable has not value.
  7. ${variable:+response}: Return response if the variable is set, otherwise return a blank string.


Variables are named storage that can hold values. The shell expands a variable when the variable's name occurs after a dollar sign ($), replacing the dollar sign and variable name with the contents of the variable. This is called variable expansion, or substitution, or occasionally replacement or even interpolation. Of these terms, expansion is used most often in documentation, but substitution is probably the clearest. Variables are assigned using an equals sign (=) with no spaces around it:
$ name=John
$ echo hello, $name
hello, John

Unlike most other programming languages, the shell uses different syntax when referring to a variable than when assigning a value to it. Variable names start with a letter or underscore, followed by zero or more letters, numbers, and underscores. Some shell programmers use all capitalized names for variables by convention. In this course, I use all capitalized names only for environment variables or special predefined shell variables (such as $IF,).Do not use mixed case; it works, but it is not idiomatic for the shell. If a variable has not been set, it expands to an empty string; there is no warning (usually) for trying to use an unset variable, which can make it hard to detect simple typos. Variables in shell are always strings; the shell does not distinguish between strings, integers, or other data types. The shell is generally considered a typeless language.