Shell Batch Script to Loop through Files
Another quick example of a tool belonging in an administrators toolbox. In our multi server hosting environment, we’re often in need for an automated, administrative command line task, and here is one to write a batch script to loop through files in the current directory and perform some actions on them.
Really, nothing is much simpler than that once we know how to it, it’s just that most administrators or developers don’t take the time to get into shell scripting. But little invested equals big time harvested.
Here is the simplest form of a bash script to loop through files, which can be built out to suit most needs.
Batch script to loop through files
#!/bin/bash FILES="*.txt" for f in $FILES do echo "Processing $f ..." # perform some action on each file. $f stores the current file name echo "Done processing $f ..." done
Now we can simply change the wildcard characters to match our future requirements, and of course fill in the body where we are doing the actual processing. After all, looping without doing anything doesn’t make much sense.
This script doesn’t do any logging or more detailed output. That can be added for more robust solutions, but for simple tasks it’s sufficient.