apachemacosshellterminalvirtual-hosts

Shell script to append new lines to etc/hosts and Apache httpd-vhosts.conf in Mac OSX 10.6


I am using Mac OSX 10.6 and doing web development on it. I know a small amount about writing shell scripts, but I am not really versed in them as of yet.

What I would like to do is to write a shell script that will simply ask for a local site alias and the document directory and it will then append the new alias onto hosts with something like "127.0.0.1 mysite.local" on a new line at the bottom of etc/hosts.

Then the script would append Apache's httpd-vhosts.conf file with something like this:

<VirtualHost *:80>
    DocumentRoot "/Repositories/myproject/mysite.com/trunk/htdocs"
    ServerName mysite.local
    ServerAlias mysite.localhost
</VirtualHost>

Then it would finally run the command to restart my Apache server. Now I know the terminal command to restart Apache, that is simple enough. I also know how to read in the site name and path from the user running the script. Such as below:

#!/bin/bash
read -p "New local site name: " site
read -p "Site path (ex:/Repositories/myproject/mysite.com/trunk/htdocs): " sitepath

What I don't know how to do is to append text to a file from terminal.

Any thoughts or helpful ideas?

Thanks, Patrick


Solution

  • Untested, but it should work:

    #!/bin/bash
    read -p "New local site name: " SITE
    read -p "Site path (ex:/Repositories/myproject/mysite.com/trunk/htdocs): " SITEPATH
    
    #/etc/hosts
    cp /etc/hosts /etc/hosts.original
    echo -e "127.0.0.1\t${SITE}.local" >> /etc/hosts
    
    #httpd-vhosts.conf
    VHOSTSFILE="/etc/apache2/httpd-vhosts.conf"
    cp $VHOSTSFILE ${VHOSTSFILE}.original
    echo "<VirtualHost *:80>" >> $VHOSTSFILE
    echo -e "\tDocumentRoot \"${SITEPATH}\"" >> $VHOSTSFILE
    echo -e "\tServerName ${SITE}.local" >> $VHOSTSFILE
    echo -e "\tServerAlias ${SITE}.localhost" >> $VHOSTSFILE
    echo '</VirtualHost>' >> $VHOSTSFILE
    
    #restart apache
    

    >> redirects the output to the given file, appending the contents to the file. I’m also using -e to allow \t to be expanded to a tab character.

    Note that you need to run this script with sudo. I've also included commands to backup the original files before modifying them, just in case.