|
Variables are containers that have names and hold information, either numbers or text. Variable names can consist of letters, numbers, and underscores (_). The name can begin with a letter or an underscore, but not a number. To create a variable, store information in it. The following are valid commands that store information: var1=3 _var2=Hello full_name="John Smith" No space is allowed before or after the =. Notice the first two commands do not use quotes around the information. The third command requires quotes because it includes a space. Without quotes, the shell would store John and see Smith as a new command. When you use a variable value, you precede the variable name with a $, such as: echo $_var2 Hello You can set one variable equal to another as follows: new_name=$full_name echo $new_name John Smith The simple script from the previous section is modified below to use a variable: #!/bin/bash # Script Name: dir2file - A simple shell script that saves a directory listing in a file status="Directory is saved" ls -l > dirlist echo $status When you run this script, the output is identical to the output in the previous section. You can store groups of values under a single variable name, useful when values are related. Complex variables that store groups of values are called arrays. For instance, you might set up the following array: full_name[1]=John full_name[2]=Smith When you use the value of an array, enclose the name in curly brackets, as follows: echo ${full_name[2]} |
|