Linux: Storing Stuff with bash - dummies

By Emmett Dulaney

You can use the features of bash when writing Linux programs called shell scripts — task-oriented collections of shell commands stored in a file. You define variables in bash just as you define environment variables. Thus you may define a variable as follows:

count=12 # note no embedded spaces allowed

To use a variable’s value, prefix the variable’s name with a dollar sign ($). For example, $PATH is the value of the variable PATH. (This variable is the famous PATH environment variable that lists all the directories that bash searches when trying to locate an executable file.) To display the value of the variable count, use the following command:

echo $count

bash has some special variables for accessing command-line arguments. In a shell script, $0 refers to the name of the shell script. The variables $1, $2, and so on refer to the command-line arguments. The variable $* stores all the command-line arguments as a single variable, and $? contains the exit status of the last command the shell executes.

From a bash script, you can prompt the user for input and use the read command to read the input into a variable. Here is an example:

echo -n "Enter value: "
read value
echo "You entered: $value"

When this script runs, the read value command causes bash to read whatever you type at the keyboard and store your input in the variable called value.

The -n option prevents the echo command from automatically adding a new line at the end of the string that it displays.