CS246-F20-1.8-BashVariables
Lecture 1.8
• bash shell variables
CS246
Shell variables
• Like in C programs, sometimes we need to remember values
– In shell scripts, often these are file/directory names, or programs to
run, or options to commands
• We will assume only string values
– Tho current bash now supports integer variables too, sort of
• A variable name is case-sensitive, and must have this format:
[_a-zA-Z][_a-zA-Z0-9]* where “*” means “0 or more”
Shell variables
• Some names are reserved (e.g., if, while)
i.e., you can’t create a variable named while
• A shell variable is declared implicitly by assigning it a value:
$ cs246assn=/u/jfdoe/cs246/a1 # bash
[Note: Don’t leave a space before or after the “=”]
• A variable’s value is dereferenced using “$” or (safer) “${}”
$ echo $cs246assn ${cs246assn}
/u/jfdoe/cs246/a1 /u/jfdoe/cs246/a1
$ cd $cs246assn
$ alias d=date
$ d
Wed 12 Sep 2012 18:15:27 EDT
$ now=d
$ now
bash: now: command not found
$ echo $now
d
$ now=$(date) # Note the “command substitution”
$ echo $now
Wed 12 Sep 2012 18:17:49 EDT
$ d # live call to date
Wed 12 Sep 2012 18:19:40 EDT
$ echo $now # variable still has old value, tho
Wed 12 Sep 2012 18:17:49 EDT
• Warning: In bash, dereferencing an undefined variable just returns an
empty string, not an error message
• Beware concatenation
– Where does this move us to? (Answer: $HOME, but why?)
• Use braces to allow concatenation with other text.
Shell variables
$ echo $xxx # no output just newline
$
$ cd $cs246assndata
$ cd ${cs246assn}data
End
CS246