Saturday, June 25, 2011

Turn a Bash array into your path

If you use Bash, do you find yourself writing your path in the following fashion?

PATH=\ 
/local/bin:\
~/bin:\
$PATH
if [ "$HOSTNAME" = server ]; then
    PATH=\ 
/usr/sbin:\
$PATH
fi

Using arrays, we can clean up this script.

saveIFS=$IFS
IFS=':'
apath=(
    /local/bin
    ~/bin
    $PATH
)
if [ "$HOSTNAME" = server ]; then
    apath=(
        /usr/sbin
        ${apath[@]}
    )
fi
apath=(${apath[@]})
strpath="${apath[*]}"
IFS=$saveIFS
PATH=$strpath

No comments: