arul's code
free code snippets

Shell script to read several conf files and create archives

Read several conf files, find user directory, create archive directory and log file

As a shell scripter, I use variations of bash script like this often. Note that this particular is not very robust, but you get the idea. As always, use code from this section at your own risk.


#!/bin/bash

# Title: Create empty files under several directories mentioned in *.conf
# Author: Arul John
# Description:
# 0. Each conf file contains key=value pairs, one per line
# 1. Read conf files in ~/config/*.conf
# 2. In each conf file, search for USERDIR=(.+) and create directory ~/$1/archive
# 3. In each ~/*/archive directory, create file webserver.log

set +x # comment this to turn off debug

# List all files and dump into $CONFFILES
CONFFILES=(`ls -1 ~/config/*.conf`)

# Loop and read 
for FILE in "${CONFFILES[@]}"
do
    # Get USERDIR value from conf file
    USERDIR=""
    while read line
    do
        if [[ "$line" =~ "USERDIR=(.+)" ]]
        then
            USERDIR=${BASH_REMATCH[1]};
        fi
    done < "$FILE"
    if [[ $USERDIR != "" ]]
    then
  echo "Creating directory ~/$USERDIR/archive"
        mkdir $USERDIR/archive/
        if [[ -d $USERDIR/archive/ ]]
        then
            echo "Creating webserver.log under archive directory"
            touch $USERDIR/archive/webserver.log
        fi
done

Share this

Last Updated: Posted on 07 Feb 2015