Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting
Prev | Chapter 4. Introduction to Variables and Parameters | Next

# 4.2. Variable Assignment

=

  the assignment operator (no space before and after)

  | Do not confuse this with = and -eq, which test, rather than assign! Note that = can be either an assignment or a test operator, depending on context.

  Example 4-2. Plain Variable Assignment

         1 #!/bin/bash
         2 # Naked variables
         3
         4 echo
         5
         6 # When is a variable "naked", i.e., lacking the '$' in front?
         7 # When it is being assigned, rather than referenced.
         8
         9 # Assignment
        10 a=879
        11 echo "The value of \"a\" is $a."
        12
        13 # Assignment using 'let'
        14 let a=16+5
        15 echo "The value of \"a\" is now $a."
        16
        17 echo
        18
        19 # In a 'for' loop (really, a type of disguised assignment):
        20 echo -n "Values of \"a\" in the loop are: "
        21 for a in 7 8 9 11
        22 do
        23   echo -n "$a "
        24 done
        25
        26 echo
        27 echo
        28
        29 # In a 'read' statement (also a type of assignment):
        30 echo -n "Enter \"a\" "
        31 read a
        32 echo "The value of \"a\" is now $a."
        33
        34 echo
        35
        36 exit 0

  Example 4-3. Variable Assignment, plain and fancy

         1 #!/bin/bash
         2
         3 a=23              # Simple case
         4 echo $a
         5 b=$a
         6 echo $b
         7
         8 # Now, getting a little bit fancier (command substitution).
         9
        10 a=`echo Hello!`   # Assigns result of 'echo' command to 'a' ...
        11 echo $a
        12 #  Note that including an exclamation mark (!) within a
        13 #+ command substitution construct will not work from the command-line,
        14 #+ since this triggers the Bash "history mechanism."
        15 #  Inside a script, however, the history functions are disabled by default.
        16
        17 a=`ls -l`         # Assigns result of 'ls -l' command to 'a'
        18 echo $a           # Unquoted, however, it removes tabs and newlines.
        19 echo
        20 echo "$a"         # The quoted variable preserves whitespace.
        21                   # (See the chapter on "Quoting.")
        22
        23 exit 0

  Variable assignment using the $(...) mechanism (a newer method than backquotes). This is likewise a form of command substitution.

         1 # From /etc/rc.d/rc.local
         2 R=$(cat /etc/redhat-release)
         3 arch=$(uname -m)

Prev | Home | Next
Introduction to Variables and Parameters | Up | Bash Variables Are Untyped