Using Variables

Programs, including shell scripts, frequently must work with data that's unknown to the programmer. For instance, you might write a script to convert a data file from one format to another by calling a series of conversion utilities. When you write the script, you don't know the original file's name, so your script uses one or more variables to hold this information. Environment variables, described earlier, in "Setting Environment Variables," are one type of variable you can use and set in shell scripts. In bash, you set a variable with the equal sign (=) operator, as shown here:


Be sure there aren't any spaces surrounding the equal sign operator. The value can be an alphanumeric string, such as hitchhiker.txt, or a numeric value, such as 42. If you surround a text string in quotes, you can include spaces in the variable's value.

To use a variable, you use its name preceded by a dollar sign ($), much as you would use a constant value. For instance, Listing 4.3 shows a script that manipulates a variable. This script prompts for and accepts input (using the echo and read commands) and then displays the result of a manipulation. This manipulation passes the variable to the cut command using a pipe, and then it extracts the second field (-f 2), as defined by spaces in the input (-d "").

Listing 4.3: Example Script Demonstrating Use of Variables

#!/bin/bash echo "Please type three words, separated by spaces:" read inputline echo -n "The second word is:" echo $inputline | cut -d " "-f2

If you type this script into a file called vardemo, make it executable, and then run it, the result might look like this:

Please type three words, separated by spaces.

one two three

The second word is: two

You can also use the variables $1, $2, and so on to refer to parameters passed to the script when you launch the program. For instance, if you type ./vardemo aparam, $1 takes on the value aparam. You can use this feature to easily send data to a script. For instance, if you want to write a script to convert one file format to another using various file-conversion utilities, you might pass the name of the original file as a parameter and refer to it as $1 throughout the script. The $0 variable refers to the name you used to launch the script, which can be useful for printing error messages or for changing the script's behavior depending upon how it's called.

0 0

Post a comment