7.2.4. Command substitutionΒΆ

The output of a command can be saved in a variable. This is done by enclosing the command between $( and ) 1:

variable=$(command)

Some examples:

thisdir=$(pwd)              # sets thisdir to the output of the command pwd
c=$(ls | grep -c ".html$")  # set c to the number of html-files (ending in .html) in
                            # this directory
c=$(ls *.html)              # sets c to the list of html-files
1

There is an older form that is still quite in use, where the command is enclosed in backticks (`), rhe first example becomes then:

thisdir=`pwd`