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
1 #!/bin/bash 2 3 echo 4 5 # When is a variable "naked", i.e., lacking the '$' in front? 6 # When it is being assigned, rather than referenced. 7 8 # Assignment 9 a=879 10 echo "The value of \"a\" is $a" 11 12 # Assignment using 'let' 13 let a=16+5 14 echo "The value of \"a\" is now $a" 15 16 echo 17 18 # In a 'for' loop (really, a type of disguised assignment) 19 echo -n "The values of \"a\" in the loop are " 20 for a in 7 8 9 11 21 do 22 echo -n "$a " 23 done 24 25 echo 26 echo 27 28 # In a 'read' statement (also a type of assignment) 29 echo -n "Enter \"a\" " 30 read a 31 echo "The value of \"a\" is now $a" 32 33 echo 34 35 exit 0 |
Example 5-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... 9 10 a=`echo Hello!` # Assigns result of 'echo' command to 'a' 11 echo $a 12 13 a=`ls -l` # Assigns result of 'ls -l' command to 'a' 14 echo $a 15 16 exit 0 |
Variable assignment using the $(...) mechanism (a newer method than backquotes)
1 # From /etc/rc.d/rc.local 2 R=$(cat /etc/redhat-release) 3 arch=$(uname -m) |