Читать книгу Linux Bible - Christopher Negus - Страница 197
Understanding shell variables
ОглавлениеOften within a shell script, you want to reuse certain items of information. During the course of processing the shell script, the name or number representing this information may change. To store information used by a shell script in such a way that it can be easily reused, you can set variables. Variable names within shell scripts are case sensitive and can be defined in the following manner:
NAME=value
The first part of a variable is the variable name, and the second part is the value set for that name. Be sure that the NAME
and value touch the equal sign, without any spaces. Variables can be assigned from constants, such as text, numbers, and underscores. This is useful for initializing values or saving lots of typing for long constants. The following examples show variables set to a string of characters (CITY
) and a numeric value (PI
):
CITY="Springfield" PI=3.14159265
Variables can contain the output of a command or command sequence. You can accomplish this by preceding the command with a dollar sign and open parenthesis, following it with a closing parenthesis. For example, MYDATE=$(date)
assigns the output from the date
command to the MYDATE
variable. Enclosing the command in back-ticks (`)
can have the same effect. In this case, the date
command is run when the variable is set and not each time the variable is read.