BASH SCRIPT TO SETUP MULTIPLE SITES ON OS X MOUNTAIN LION
after the mac os mountain lion update, my local web server stopped working. boo hiss. i had to google my way to fixing it. it took some time, but all is now well.
all that effort made me want to streamline the process for adding and setting up additional sites. since i don't know much about writing bash scripts it would be a learning experience too.
i needed the script to take in a server name and a directory path. using this information it would add an entry to the mac hosts file and a virtualhost block to the apache config file. then it would restart apache.
An example usage would look like so:
makesite -s somesite.localhost -d pathtodocumentroot
first off, some bash basics. how to create and run a script.
ok next hurdle, how to parse arguments. my script would have 3 options, -h for help, -s for the server name and -d for the directory that the site will reside in.
Once the arguments were sorted, the script would have to write to the mac host file.
echo 127.0.0.1 somesite.local >> '/private/etc/hosts';
...then the virtual host block via a heredoc
cat >> "/private/etc/apache2/extra/httpd-vhosts.conf" << EOD <VirtualHost *:80> DocumentRoot "pathtodocumentroot" ServerName somesite.local <Directory "pathtodocumentroot"> AllowOverride All Options All </Directory> </VirtualHost> EOD
...but only on the conditional that the user has specified values for -s and -d
if [[ -z $SERVERNAME ]] || [[ -z $DIRNAME ]] then usage exit 1 else do the good stuff... fi
...and it would be nice if the script wrote to the files only if the user was root
if [[ -z $SERVERNAME ]] || [[ -z $DIRNAME ]] then usage exit 1 else if [ "(id -u)" != "0" ] then echo "This script requires root." exit 1 else do the good stuff... fi fi
and then restart apache.
Finally to finish things off, the script was moved so it would be available as a systemwide executable.
So that was the journey for my very first bash script.