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

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


Untested, but it should work:

#!/bin/bashread -p "New local site name: " SITEread -p "Site path (ex:/Repositories/myproject/mysite.com/trunk/htdocs): " SITEPATH#/etc/hostscp /etc/hosts /etc/hosts.originalecho -e "127.0.0.1\t${SITE}.local" >> /etc/hosts#httpd-vhosts.confVHOSTSFILE="/etc/apache2/httpd-vhosts.conf"cp $VHOSTSFILE ${VHOSTSFILE}.originalecho "<VirtualHost *:80>" >> $VHOSTSFILEecho -e "\tDocumentRoot \"${SITEPATH}\"" >> $VHOSTSFILEecho -e "\tServerName ${SITE}.local" >> $VHOSTSFILEecho -e "\tServerAlias ${SITE}.localhost" >> $VHOSTSFILEecho '</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.


I made some tweaks and did some extra stuff in the above answer, because this didn't work for me but it helped me to come up with another solution. This answer is only for Mac users.

First go in your /etc/apache2/httpd.conf and uncomment virtual host reference, which is this line Include /private/etc/apache2/extra/httpd-vhosts.conf

Now create a bash file I did that in my user’s home named as imran, you need to replace it with your username.

I placed it inside /Users/imran named as create_new_site.sh. I gave it executeable permissions, so it can be easily executed using chmod +x create_new_site.sh

Code for the script is as below:

#!/bin/bashread -p "New local site name (prefix to .local): " SITESITEPATH=$SITEsudo chmod -R a+w /Users/imran/Sites/webSITEPATH="/Users/imran/Sites/web/${SITEPATH}"mkdir -p $SITEPATH#/etc/hostscp /etc/hosts /etc/hosts.originalecho -e "127.0.0.1\t${SITE}.local" >> /etc/hosts#httpd-vhosts.confVHOSTSFILE="/etc/apache2/extra/httpd-vhosts.conf"cp $VHOSTSFILE ${VHOSTSFILE}.originalecho "<VirtualHost *:80>" >> $VHOSTSFILEecho -e "\tDocumentRoot \"${SITEPATH}\"" >> $VHOSTSFILEecho -e "\tServerName ${SITE}.local" >> $VHOSTSFILEecho '</VirtualHost>' >> $VHOSTSFILEecho '<?php phpinfo();' > "${SITEPATH}/phpinfo.php"sudo chmod -R a+w $SITEPATH#restart apachesudo apachectl restartecho "All done! visit, let's visit http://${SITE}.local/phpinfo.php"

Once that is done you can start creating new sites using sudo ./create_new_site.sh. Remember that you need to be in your home directory, which you can go via cd ~ command. Now let's suppose you created a site with name test. You should be able to visit http://test.local/phpinfo.php to see your vhost working.