WSU logo


College of Engineering & CS
Wright State University
Dayton, Ohio 45435-0001

CEG 333: Introduction to Unix

Prabhaker Mateti

Bash: Variables and Assignments


Using Variables

Shell variables are declared with the set command, or simply by setting them equal to something. For example, test=1 creates a variable named "test" containing the value "1". Unlike variables in some other languages, a type is not necessary; the values are stored as strings.

Note: there must not be whitespace around the equals sign. test = 1 will not work!

Variables are referenced by their names, and must always be prefixed with a "$". (echo $test prints "1", but echo test just prints "test".) To avoid confusion with the $ prompt character, in these examples the prompt changes % by setting the prompt variable named PS1: PS1=%

An example:

      % test=txt
      % echo $test
      txt
      % test=file.$test
      % echo $test
      file.txt
    

Note: if a variable is set in a sub-shell, such as a script, it's value isn't changed in the invoking shell—the new value is lost as soon as the script finishes. Use export VARIABLE... to propagate the change up shell levels if desired.

Manipulating Variables

Complex operations may be performed on variables by surrounding them with curly braces ("{}"). The two most important of these are "#" and "%", which remove text from the beginning and end of a variable, respectively.

An example:

      $ test=txt
      $ echo ${test#t}
      xt
      $ echo ${test%t}
      tx
      $ test=file.lst
      $ echo ${test%lst}txt
      file.txt
      $ echo $test
      file.lst
    

Only the value substituted into the command changes. The string stored in the variable is not affected.