Bash Scripts


Here are some misc. bash scripts that I find handy. Some of these are mine, some I have taken from others. I use Ubuntu and Apache, so any directories or OS commands referenced here are applicable to that stack.

addwebsite.sh

For folks running multiple websites on the same machine, this takes some of the pain from quickly getting a new site configured.

#!/bin/bash
# addwebsite.sh    
# Usage: ./addwebsite.sh example.com

if [ $# -ne 1 ]
then
  echo "Please specify the sitename such as example.com"
  exit 1
fi

ADMIN_NAME=webadmin_username
SITENAME=$1

# create directory for site in ADMIN_NAME
mkdir /home/${ADMIN_NAME}/htdocs/${SITENAME}
mkdir /home/${ADMIN_NAME}/log/${SITENAME}

# Files in web-accessable directories belong to user's special group that www-data belongs to
chown -R $ADMIN_NAME:${ADMIN_NAME}_GRP /home/$ADMIN_NAME/htdocs

# chmod g+w make all directories group-writeable, so web-scripts can save
# chmod g+s make all directories pass their group to their children when new children are created
# This will recursively search your directory tree & chmod all directories only.
find /home/$ADMIN_NAME/htdocs/${SITENAME} -type d -exec chmod g+w+s {} \;

#actually, we need all files to be group writeable, for log files, etc.
chmod -R g+w /home/$ADMIN_NAME/htdocs/${SITENAME}

#now, copy template file and change it for this site
sed "s/template.tld/${SITENAME}/g" /etc/apache2/sites-available/template.tld > /etc/apache2/sites-available/${SITENAME}

#replace ADMIN_NAME in template with $ADMIN_NAME defined above
sed -i "s/ADMIN_NAME/$ADMIN_NAME/g" /etc/apache2/sites-available/${SITENAME}

# enable the site
a2ensite ${SITENAME} > /dev/null

# reload apache
/etc/init.d/apache2 reload > /dev/null

echo "Don't forget to add ${SITENAME} to the DNS now!"

Template file

For the above to work, we also need to have created a template.tld file in /sites-available directory. here is the one I use. After the site is up and running, you can layer in extra configurations you need.

# Public HTML Folder
# template.tld

<VirtualHost *:80>
# Admin email, Server Name (domain name) and any aliases
ServerAdmin webmaster@template.tld
ServerName template.tld
ServerAlias *.template.tld


# Index file and Document Root (where the public files are located)
DirectoryIndex index.php index.html
DocumentRoot /home/ADMIN_NAME/htdocs/template.tld

<Directory /home/ADMIN_NAME/htdocs/template.tld/>
 AllowOverride All
</Directory>

# Custom log file locations
LogLevel warn
ErrorLog /home/ADMIN_NAME/log/template.tld/error.log
CustomLog /home/ADMIN_NAME/log/template.tld/access.log combined

</VirtualHost>