Click Here to buy the full 72-page PDF for only £4.99, $9.99 or €6.99,
or the Kindle eBook (UK here - more countries and details here)

This site hosted by HostGator:
Use code STEVEPARKER25 and get 25% off.

12. External Programs

External programs are often used within shell scripts; there are a few builtin commands (echo, which, and test are commonly builtin), but many useful commands are actually Unix utilities, such as tr, grep, expr and cut.

The backtick (`)is also often associated with external commands. Because of this, we will discuss the backtick first.
The backtick is used to indicate that the enclosed text is to be executed as a command. This is quite simple to understand. First, use an interactive shell to read your full name from /etc/passwd:

$ grep "^${USER}:" /etc/passwd | cut -d: -f5
Steve Parker

Now we will grab this output into a variable which we can manipulate more easily:

$ MYNAME=`grep "^${USER}:" /etc/passwd | cut -d: -f5`
$ echo $MYNAME
Steve Parker

So we see that the backtick simply catches the standard output from any command or set of commands we choose to run. It can also improve performance if you want to run a slow command or set of commands and parse various bits of its output:


#!/bin/sh
find / -name "*.html" -print | grep "/index.html$"
find / -name "*.html" -print | grep "/contents.html$"

This code could take a long time to run, and we are doing it twice!
A better solution is:


#!/bin/sh
HTML_FILES=`find / -name "*.html" -print`
echo "$HTML_FILES" | grep "/index.html$"
echo "$HTML_FILES" | grep "/contents.html$"
Note: the quotes around $HTML_FILES are essential to preserve the newlines between each file listed. Otherwise, grep will see one huge long line of text, and not one line per file.

This way, we are only running the slow find once, roughly halving the execution time of the script.

We discuss specific examples further in the Hints and Tips section of this tutorial.

Click Here to buy the full 72-page PDF for only £4.99, $9.99 or €6.99,
or the Kindle eBook (UK here - more countries and details here)

This site hosted by HostGator:
Use code STEVEPARKER25 and get 25% off.
Steve's Bourne / Bash shell scripting tutorial
Share on Twitter Share on Facebook Share on LinkedIn Share on Identi.ca Share on StumbleUpon

Get the Book:

My Shell Scripting Book:
    Shell Scripting, Expert Recipes for Linux, Bash and more
is available online and from all good booksellers.

Buy my 600-page Shell Scripting Book...

From Amazon USA:

Or from other retailers

Facebook:

You can also join a Shell Scripting community on Facebook:

Get the Tutorial as a PDF:

Shell Scripting Tutorial
Buy the 72-page PDF (£4.99 / $9.99 / €6.99) of this tutorial
(Free Sample)

Get the Tutorial on Kindle:

For Kindle from Amazon USA:
For Kindle from Amazon UK:

And you can always Download my Free Shell Scripting Cheatsheet PDF

DefectiveByDesign.org