Jun
3rd

Update a file in multiple home directories

Filed under My Cool Scripts | Posted by Gary

A few times now I’ve had to update a file in multiple home directories. I did a lot of searching and using tips and examples from several sites, plus the little bit of experience I had with shell scripts (hey, I may be a geek but I’m not a bash geek! 🙂 ), I wrote this little script. It looks through all the home directories for a specific file, updates it with a new version and then changes the permissions to the correct owner for that home directory. Cool eh?

In this case I was updating wordpress’s rss.php file for a bunch of hosting accounts. Here’s the script:

========== 8< ========================

#!/bin/sh

# These next 3 lines should be on a single line.
for file in $(find /home -name "rss.php" | 
grep 'wp-includes/rss.php' | xargs ls -l | 
grep 'rss.php' | awk '{print $9}')
# Followed by this line and the rest of the script
do
    owner=$(ls -al $file | awk '{print $3}');
    mv $file ${file}.bak.php
    cp /updates/new_wp_rss.php $file
    chown $owner $file
    chgrp $owner $file
    echo "Changed owner to $owner for $file"
done

=================== >8 ================

The script backs up the existing file and copies a new one from the /updates directory. It then changes the ownership on the new file so that it is correct for the home directory that it is currently in. I also have it print that out to screen … that’s just a bit of paranoia – I like to see what’s happening :).

You may be wondering about the second ‘grep’ on the first line of the script. It’s in there because I use this script fairly regularly and in some cases I had a mix of old and new files. I only wanted to update the old files, so I was grepping the size of the file in that second grep. Instead of grep ‘rss.php’ it was something like grep’15347′ so that it would find all of the files named in the first grep, but only update them if they were a specific size.

You must be logged in to post a comment.