
bash Beginnings
|
217
Variables
bash is a programming language, and programming languages have common fea-
tures. One of the most basic is the variable: a symbol that contains a value. bash vari-
ables are strings unless you specify otherwise with a
declare statement. You don’t
need to declare or define bash variables before you use them, unlike with many other
languages.
A variable’s name is a string starting with a letter and containing letters, numbers, or
underscores (
_). A variable’s value is obtained by putting a $ character before the
variable’s name. Here’s a shell script that assigns a string value to the variable
hw,
then prints it:
#!/bin/bash
hw="hello world"
echo $hw
The variable hw is created by the assignment in line 2. In line 3, the contents of the
variable
hw will replace the $hw reference. Because bash and other shells treat
whitespace characters (spaces and tabs) as command argument separators rather
than normal argument characters, to preserve them you must surround the whole
string with double quote (
") or single quote (') characters. The difference is that shell
variables (and other special shell syntax) are expanded within double quotes and
treated literally within single quotes. Look at the difference in output from the two
echo commands in the following script:
admin@server1:~$ cat hello2
#!/bin/bash
hw="hello world"
echo "$hw"
echo '$hw'
admin@server1:~$ ./hello2
hello world
$hw
admin@server1:~$ ...