Command Substitution
From the discussion so far, we’ve seen two ways of getting values into variables: by assignment statements and by the user supplying them as command-line arguments (positional parameters). There is another way: command substitution, which allows you to use the standard output of a command as if it were the value of a variable. You will soon see how powerful this feature is.
The syntax of command substitution is: [55]
$(UNIX command)The command inside the parentheses is run, and anything the command writes to standard output is returned as the value of the expression. These constructs can be nested, i.e., the UNIX command can contain command substitutions.
Here are some simple examples:
The value of $(pwd) is the current directory (same as the environment variable $PWD).
The value of $(ls $HOME) is the names of all files in your home directory.
The value of $(ls $(pwd)) is the names of all files in the current directory.
To find out detailed information about a command if you don’t know where its file resides, type ls -l $(type -path -all command-name). The -all option forces type to do a pathname look-up and -path causes it to ignore keywords, built-ins, etc.
If you want to edit (with vi) every chapter of your book on bash that has the phrase “command substitution,” assuming that your chapter files all begin with ch, you could type:
vi $(grep -l 'command substitution' ch*)The -l option to grep prints only the names of files that contain matches.
Command substitution, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access