Command Substitution

One way of handling variables automatically is by using command substitution. This is a technique that puts the result of a command in a variable that can be used in a script (or on the command line). This technique is especially useful if you need to work with information that changes often or automatically. To use command substitution, you need to put the command you want to use between backticks; for example, echo swhoamis would put the result of the whoami command in the echo command.

An example of this is a script that refers to the directory where kernel modules are installed. This directory changes with every kernel update that is installed, so it's not really a good idea to use hard references to this directory everywhere. Command substitution is an ideal solution.

You can display the name of the current kernel version with the uname -r command. So instead of referring to the directory /lib/modules/2.6.16-308a (or whatever the name of the module directory for the currently loaded kernel is), you can refer to /lib/modules/suname -rs instead. The example script in Listing 27-9 shows how you can use command substitution.

Listing 27-9. Example of Command Substitution

# Copy a kernel module to the appropriate directory

# Usage: ./modcop echo Enter the full path name of the file that you want to copy read file cp $file /lib/modules/suname -rs

In this example, the script first asks the user to input the complete name of the file he wants to copy. Next, it will copy the file to the directory where the current kernel stores its kernel modules.

Was this article helpful?

0 0

Post a comment