Creating a simple bash script

The simplest scripts are those that string together some basic commands and perhaps do something useful with the output. Of course, this can be done with a simple alias or function, but eventually you’ll have a requirement that exceeds a one-line request, and a shell script is the natural solution. Aliases and functions have already been used to create a rudimentary new command, lsps. Now let’s look at a shell script (Example 13-6) that accomplishes the same thing.

Example 13-6. The lsps script
# A basic lsps command script for bash
ls -l $1
ps -aux | grep `/bin/basename $1`

As you can see, the commands used in this simple script are identical to those used in the alias and in the function created earlier. To make use of this new file, instruct your currently running bash shell to source it, giving it an option for the $1 positional parameter:

$ source ./lsps /usr/sbin/httpd

If you have /usr/sbin/httpd running, you should receive output similar to that found previously for the alias. By replacing the word source with a single dot, you can create an alternate shorthand notation to tell bash to source a file, as follows:

$ . ./lsps /usr/sbin/httpd

Another way to invoke a script is to start a new invocation of bash and tell that process to source the file. To do this, simply start bash and pass the script name and argument to it:

$ /bin/bash ./lsps /usr/sbin/httpd

This last example gives us the same result; however, it is significantly different from the alias, ...

Get LPI Linux Certification in a Nutshell, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.