Advanced Bash-Scripting Guide: A complete guide to shell scripting, using Bash | ||
---|---|---|
Prev | Chapter 5. Introduction to Variables and Parameters | Next |
the assignment operator (no space before & 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 5-2. Plain Variable Assignment
#!/bin/bash echo # When is a variable "naked", i.e., lacking the '$' in front? # When it is being assigned, rather than referenced. # Assignment a=879 echo "The value of \"a\" is $a" # Assignment using 'let' let a=16+5 echo "The value of \"a\" is now $a" echo # In a 'for' loop (really, a type of disguised assignment) echo -n "The values of \"a\" in the loop are " for a in 7 8 9 11 do echo -n "$a " done echo echo # In a 'read' statement (also a type of assignment) echo -n "Enter \"a\" " read a echo "The value of \"a\" is now $a" echo exit 0 |
Example 5-3. Variable Assignment, plain and fancy
#!/bin/bash a=23 # Simple case echo $a b=$a echo $b # Now, getting a little bit fancier... a=`echo Hello!` # Assigns result of 'echo' command to 'a' echo $a a=`ls -l` # Assigns result of 'ls -l' command to 'a' echo $a exit 0 |
Variable assignment using the $(...) mechanism (a newer method than backquotes)
# From /etc/rc.d/rc.local R=$(cat /etc/redhat-release) arch=$(uname -m) |