OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

Command Substitution

Command substitution allows us to use the output of a command as an expansion:



[me@linuxbox ~]$ echo $(ls)

Desktop Documents ls-output.txt Music Pictures Public Templates Videos

[me@linuxbox ~]$ echo $(ls)

Desktop Documents ls-output.txt Music Pictures Public Templates Videos


One of my favorites goes something like this:



[me@linuxbox ~]$ ls -l $(which cp)

-rwxr-xr-x 1 root root 71516 2007-12-05 08:58 /bin/cp

[me@linuxbox ~]$ ls -l $(which cp)

-rwxr-xr-x 1 root root 71516 2007-12-05 08:58 /bin/cp


Here we passed the results of which cp as an argument to the ls command, thereby getting the listing of of the cp program without having to know its full pathname. We are not limited to just simple commands. Entire pipelines can be used (only partial output


shown):



[me@linuxbox ~]$ file $(ls -d /usr/bin/* | grep zip)

/usr/bin/bunzip2: symbolic link to `bzip2'

/usr/bin/bzip2: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, stripped

/usr/bin/bzip2recover: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, stripped

/usr/bin/funzip: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, stripped

/usr/bin/gpg-zip: Bourne shell script text executable

/usr/bin/gunzip: symbolic link to `../../bin/gunzip'

/usr/bin/gzip: symbolic link to `../../bin/gzip'

/usr/bin/mzip: symbolic link to `mtools'

[me@linuxbox ~]$ file $(ls -d /usr/bin/* | grep zip)

/usr/bin/bunzip2: symbolic link to `bzip2'

/usr/bin/bzip2: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, stripped

/usr/bin/bzip2recover: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, stripped

/usr/bin/funzip: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, stripped

/usr/bin/gpg-zip: Bourne shell script text executable

/usr/bin/gunzip: symbolic link to `../../bin/gunzip'

/usr/bin/gzip: symbolic link to `../../bin/gzip'

/usr/bin/mzip: symbolic link to `mtools'


In this example, the results of the pipeline became the argument list of the file com- mand.

There is an alternate syntax for command substitution in older shell programs which is also supported in bash. It uses back-quotes instead of the dollar sign and parentheses:


[me@linuxbox ~]$ ls -l `which cp`

-rwxr-xr-x 1 root root 71516 2007-12-05 08:58 /bin/cp

[me@linuxbox ~]$ ls -l `which cp`

-rwxr-xr-x 1 root root 71516 2007-12-05 08:58 /bin/cp


Top OS Cloud Computing at OnWorks: