Now that you have used variables and arguments, you are probably wondering how to have your scripts do something simple like adding two numbers together and storing the results in a variable. The answer to this lies in using a powerful feature of Unix shells called backquoted commands . Backquoted commands enable you to incorporate one command line within another command line. The backquote (also called a backtick ) is the ` character, usually found in the upper left corner of your keyboard, just above . The backquote ` is not the same as the apostrophe, ' , so be careful not to confuse the two.
You use backquoted commands in scripts any time you want to store the output of a command line in a variable. You also use them when you want to create a command line in which part of the command line comes from the output of some other command.
We mentioned the use of backquotes briefly in Chapter 2, and now we will go into more detail about them.
To use backquotes in a command line:
To save the output of a command in a variable:
#!/bin/sh # This script uses a backquoted command. today=`date "+%A, %B %d"` echo "Hello $USER, today is $today"
localhost:~ vanilla$ ./script.sh Hello vanilla, today is Monday, June 17 [localhost:~]
You can (and should) test whatever you put in backquotes by typing it at a shell prompt first.
Two Unix commands do floating-point arithmetic at the command line or in a shell script: dc and bc . Both are fairly complex programs. The dc command uses "reverse Polish notation" (developed in 1920 by Jan Lukasiewicz; see the RPN page on MoHPC, www.hpmuseum.org/rpn.htm), in which you enter numbers and operators and then ask for a result. For example, to use dc to divide 23 by 5 with a precision of four decimal places, you would enter
echo "4 k 23 5 / p" dc
This is not pretty. The equivalent command line for bc is only slightly better:
echo "scale=4; 23 / 5" bc
Read the man pages for these commands for the full details.