Saturday, December 5, 2009

Nesting commands in a bash shell

How many levels deep can you run commands under bash?
Using the back tick operator it is possible to execute a command first and pass the result backwards.

bash-magic > more `find /etc/ -depth -name resolv.conf -print`
::::::::::::::
/etc/resolv.conf
::::::::::::::
# Generated by NetworkManager
nameserver 8.8.8.8
nameserver 8.8.4.4

This can come in quite handy when using the command line. The example above execs a find command and passes the output to the input of the more command.

The backticks ` ` can only do one level of depth within the shell. But what happens if you need to string more than 2 commands together? Backticks just will not cut it.

Enter the almighty parentheses ().
bash-magic > ps -ef $(grep $(id))

Here is an example of 3 commands deep within the shell. The ps -ef command calls a subcommand grep which calls a subcommand id. This could have been accomplished using ps -ef | grep `id` but for examples sake we are using parentheses ().


No comments:

Post a Comment