Any Unix shell script longer than a line will most likely involve using variables. Variables are used to store temporary values to simply using them in various Unix commands of your script. The beauty of using variables is that they can be evaluated and set ones, but then reused as many times as you like without your shell interpreter having to re-evaluate them again.
Defining a variable in Unix shell
To specify a value for a variable, you need to decide on the variable name – can be any word or combination of English alphabet symbols and digits, and specify the value.
In Bourne shell (sh), Bourne Again Shell (bash) and Korn Shell (ksh), here's how you would define a new variable and assign it a value:
In C-Shell (csh), it's done like this:
setenv CONFIG_FILE "/etc/myfile"
Basic variables usage
To access the value of a variable, you need to use the same variable name, but with a dollar sign in front of it, like this:
Important: to set a new value to the variable, you use just the variable name like CONFIG_FILE, but to access this value later you need to use the $CONFIG_FILE form.
The most basic way to use variables is to assign them constant values at the beginning of your script. This is a good way to define locations of standard files or directories your script will work with, etc:
#!/bin/sh # CONFIG_FILE=/etc/myfile MY_DIR=/etc echo $CONFIG_FILE
Using output of Unix commands to set variables
One of the best things about shell scripting is that it's very easy to use any Unix command to generate the output and use it to set the variable.
In this example, I'm running a date command and saving its output as values for my variables:
ubuntu$ cat /tmp/1.sh
#!/bin/sh # STARTED=`date` sleep 5 FINISHED=`date` # echo "Script start time: $STARTED" echo "Script finish time: $FINISHED"
If I run this simple script, I see the following:
Script start time: Wed May 7 04:56:51 CDT 2008
Script finish time: Wed May 7 04:56:56 CDT 2008
The same approach can be used for practically any scenario.
Here's an example of using uname command to extract some useful information about our system:
#!/bin/sh # STARTED=`date` NODE=`uname -n` OS=`uname -o` CPU=`uname -p` FINISHED=`date` # echo "Nodename: $NODE" echo "OS type: $OS" echo "Processor: $CPU" echo "Script start time: $STARTED" echo "Script finish time: $FINISHED"
And this is how it works:
ubuntu$ /tmp/1.sh Nodename: ubuntu OS type: GNU/Linux Processor: unknown Script start time: Wed May 7 05:05:31 CDT 2008 Script finish time: Wed May 7 05:05:31 CDT 2008
That's it for today! Let me know what next topic about Unix shell scripting you'd like to see covered, and I'll do my best to explain it in the coming posts.
If you want to learn more, here's a great book: