This is a personal blog. All opinions expressed are my own personal opinions, not those of my employer.

bash scripting

bash scripting: perform the same actions on many variables

I just had to write a script for James which would (a) download a bunch of .tar.gzs from various sourceforge projects, and (b) untar those files, and store the directories for later use.

Here's what I came up with:

#!/bin/bash

SRC_XMLRPC="http://prdownloads.sourceforge.net/xmlrpc-epi/xmlrpc-epi-0.51.tar.gz"
SRC_ELFIO="http://prdownloads.sourceforge.net/elfio/ELFIO-1.0.3.tar.gz"

for SRCVAR
in ${!SRC_*}
do
  TAROUT=$(curl -s --location ${!SRCVAR}  | tar -zxvf -)
  export DIR_${SRCVAR/SRC_/}=$(echo $TAROUT | cut -f 1 -d \ )
done

New things I learnt:

${!SRC_*} expands to an array containing the names of all variables whose names start with SRC_
${!SRCVAR} expands to the value of the variable whose name is the value of $SRCVAR - ie, one level of indirection.
${SRCVAR/SRC_/} - well, think what :s/$SRCVAR/SRC_// would do in vi (if vi knew how to expand $SRCVAR)...

Bash is the rocks.

One thing that annoys me: that cut. That causes a fork. Forks is bad. The forks for curl and tar - those, I can't avoid, but this fork should be avoidable. I'd like to avoid that fork if I could.

Update: Fork Avoided!

#!/bin/bash -x

BASEDIR=`pwd`

SRC_XMLRPC="http://prdownloads.sourceforge.net/xmlrpc-epi/xmlrpc-epi-0.51.tar.gz"
SRC_ELFIO="http://prdownloads.sourceforge.net/elfio/ELFIO-1.0.3.tar.gz"

for SRCVAR
in ${!SRC_*}
do
  TAROUT=$(curl -s --location ${!SRCVAR}  | tar -zxvf -)
  export DIR_${SRCVAR/SRC_/}=${TAROUT%%/*}
done
Syndicate content