Bash Command Substitution

Bash command substitution performs a given command replacing the marker with the resulting standard output. It is particularly useful when you want to store the output of a command in a variable or as an alternative method of chaining multiple commands together.

Bash command substitution is achieved by wrapping your target code in braces with a preceding $, or backticks `. For example:

$ date +%d-%b-%Y

You can put the output of that command into a variable using command substitution as follows:

$ today =$(date +%d-%b-%Y)
$ echo today

Alternatively, with backtick style:

$ today =`date +%d-%b-%Y`
$ echo today

You can also perform command substitution inside an echo command:

echo -e "List of logged on users and what they are doing:\n $(w)"

You can also feed the results of command substitutions into a for loop as follows:

for f in $(ls /etc/*.conf)
   echo "$f"

This example is a little contrived as you can achieve the same result with for f in /etc/*.conf

Continue reading

Find all files containing a given string  bash

A quick one-liner to recursively search files for a given text string. Open up a terminal session and enter the following - replacing "foo" with the text to search for. find . -exec grep -l "foo" {} \; You can also limit the search to files with a particular extension (e.g. HTML or … More