Tutorials

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:

python
$ date +%d-%b-%Y
21-Jul-2012

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

python
$ today =$(date +%d-%b-%Y)
$ echo today
21-Jul-2012

Alternatively, with backtick style:

python
$ today =`date +%d-%b-%Y`
$ echo today
21-Jul-2012

You can also perform command substitution inside an echo command:

python
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:

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

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

PyQt/PySide 1:1 Coaching with Martin Fitzpatrick

Save yourself time and frustration. Get one on one help with your Python GUI projects. Working together with you I'll identify issues and suggest fixes, from bugs and usability to architecture and maintainability.

Book Now 60 mins ($195)

Elsewhere

Find all files containing a given string
Collaborate in the shell with screen (multiuser)
Use bash brace expansion to save {hours,days}
Analysis of 1D Bruker NMR data with Pathomx v3.0 (Release candidate)