Top Nav

Archive | Bash Scripting

Apache Watch Script

Here’s a trivial old script that I sometimes use to monitor for rough processes running on the apache user:



How-to Cut With Multi-Character Delimiter

The “cut” command is great for splitting a string on a single character and extracting specific fields. But it will not work with multi-character delimiters. Here’s a simple replacement using awk that will get the job done. Let’s assume you have a string like:

We could extract the value of “arg3” using cut with:

But this assumes that there are always the same number of proceeding args:

Now lets do it with awk:

But what if the args are in different order? The we can use sed:



Cronjob for ClamAV

ClamAV can be useful for things like scanning a web root for viruses. Use this handy script with a cron job to setup nightly scans that send an email report.

Follow the directions on the site to install. We’ve modified the last line of the script so that it will work properly. Comment out the last line in /usr/local/bin/clamav-cron and add the following line to fix portion of the script that sends email. Make sure mailx is installed.

You can use crontab -e to open up the cron editor and add the following entry:

This tells ClamAV to scan /var/www/vhosts each morning at 3am and send an email report.


Copy Files & Create Missing Directories

I needed to find all the image files in a large directory tree and then copy them to a new directory tree while preserving the directory structure. Here’s my solution:

1. Find the files and save list to a file:

This command demonstrates using the -exec option on “find” to feed the “file” command.

2. Copy each file on the list, creating sub directories as needed:

This command demonstrates a one line while loop feed by input redirection. Also notice the “–parents” option on the “cp” command.


Bash Loops

Here’s a basic loop in Bash:

Notice that it iterates over a space delimited string of values.

If you have a comma delimited list then you can do something like this:

IFS is the “internal field separator” which defaults to a blank space. We save the original IFS and change it to a comma. Then once we’re done we restore the original IFS.

Here are some links to additional examples: