Expanding Commands
With command substitution, you essentially let the shell handle a command's output rather than the command itself. This nifty trick allows one command's output to be passed as an argument to another command. You've got two ways to do this:
$(command)
`command`
Just a heads up, those are backticks on the latter, not your usual single quotes.
In this approach, the command can have all the bells and whistles: options, metacharacters, and arguments. Here's an example of command substitution in action:
In this example, the command substitution is done before the vi
command is run. It runs as follows:
First, the
find
command starts at the/home
directory and prints out all of the files and directories below that point in the filesystemThe output is piped to the
grep
command, which filters out all files except for those that include the string xyzzy in the filenameFinally, the
vi
command opens all filenames for editing (one at a time) that include xyzzy.
If you run the above steps and are not familiar with vi, you can type :q!
to exit the file.
This particular example is useful if you want to edit a file for which you know the name, but not the location. As long as the string is uncommon, you can find and open every instance of a filename existing beneath a point you choose in the filesystem.
In other words, don’t use grep
from the root filesystem or you’ll match and try to edit several thousand files.
Expanding Arithmetic Expressions
Occasionally, you might fancy passing some maths results over to a command. There are a couple of ways you can expand a mathematical expression and hand it over to the shell:
or
Expanding Variables
Variables that store information within the shell can be expanded using the dollar sign $
metacharacter.
When you expand an environment variable on a command line, what you'll see printed is the variable's value, not its name, like this:
Last updated