Running All Scripts in a Directory
Problem
You want to run a series of scripts, but the list keeps changing; you’re always adding new scripts, but you don’t want to continuously modify a master list.
Solution
Put the scripts you want to run in a directory, and let bash run everything that it finds. Instead of keeping a master list, simply look at the contents of that directory. Here’s a script that will run everything it finds in a directory:
for SCRIPT in /path/to/scripts/dir/* do if [ -f $SCRIPT -a -x $SCRIPT ] then $SCRIPT fi done
Discussion
We will discuss the for loop
and the if statement in greater
detail in Chapter 6, but this gives
you a taste. The variable $SCRIPT will
take on successive values for each file that matches the wildcard
pattern *, which matches everything in the current directory (except
invisible dot files, which begin with a period). If it is a file (the
-f test) and has execute permissions
set (the -x test), the shell will
then try to run that script.
In this simple example, we have provided no way to specify any arguments to the scripts as they are executed. This simple script may work well for your personal needs, but wouldn’t be considered robust; some might consider it downright dangerous. But we hope it gives you an idea of what lies ahead: some programming-language-style scripting capabilities.
See Also
Chapter 6 for more about
forloops andifstatements
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access