If you, like me, strive to keep a well organized and modular configuration setup, sooner or later will split your bash configuration into multiple files. And if you want it to be valid for multiple machines you’ll appreciate the following function:

source_if_exists () {
    for i_; do test -f "$i_" && source "$i_"; done
}

This way, you can try to process other configuration fragments only when they exist:

source_if_exists ${HOME}/etc/bash_completion

Another common need for bash configuration is to either append or prepend paths to an environment variable. When doing a configuration for multiple machines it is always a pain to make sure those paths exist. These functions take care of that making adding directories to the path a breeze:

safe_prepend_path() {
    VAR=$1
    shift
    VAL=$(eval echo \$${VAR})
    for i_; do
        test -d "$i_" && VAL=$i_${VAL:+":$VAL"}
    done
    eval export ${VAR}=$(echo ${VAL})
}

safe_append_path() {
    VAR=$1
    shift
    VAL=$(eval echo \$${VAR})
    for i_; do
        test -d "$i_" && VAL=${VAL:+"$VAL:"}$i_
    done
    eval export ${VAR}=$(echo ${VAL})
}

Example:

safe_prepend_path PATH /opt/local/bin ${HOME}/bin
safe_append_path MANPATH /opt/local/man ${HOME}/man

Also, it is not unusual to have some path variables with duplicate entries, which is not very efficient. This function makes sure that a path only occurs once, and retains only the first occurrence, thus keeping the search order intact.

unique_path() {
    eval export $1=$(echo $(eval echo \$${1}) | \
        awk -F:                   \
        '{ a[$1];                 \
           printf "%s",$1;        \
           for(i=2;i<=NF;i++) {   \
             if(!($i in a)) {     \
               printf ":%s",$i;   \
             };                   \
             a[$i];               \
           };                     \
           printf "\n";           \
         }'
)
}

Example:

unique_path PATH
unique_path MANPATH

Nokia sure knows how to make very weird decisions. So you’d think that if you manage an email service in order to add to your value proposition in the mobile space, upon deciding to sub-contract it to Yahoo, you’d make sure your current users would be able to migrate…


(Amazon)

Half a decade ago, while discussing interesting books on software development, a good friend of mine recommended me the book The Soul of a New Machine. Today I happened to come across my copy of the book and was surprised at how much of a strong impression it made.
It only makes it ring closer to home the fact that I work for the company that ultimately acquired Data General…

keep looking »