Reprocessing imagery with GDAL and BASH — and then cleaning up afterward

I just can’t seem to get away from Bash. One day I promise to do the same work with Python, but for now, the following will take your directory of 3-band imagery, extract the first band, and if it succeeds, delete your original file. Seeing as I had almost 300GB of imagery, and very little space left, this kind of housekeeping was necessary (my other two bands were vestiges of a stage that used PNG as a temporary format– but each band was identical).


for name in $( ls ????_???.tif);                                 # e.g. "2765_560.tif"

    basename1=`echo $name | awk -F'.' '{print $1}'`              # Split off non-extension portion of name

    if [ -f $basename1_"1.tif" ]
      echo $basename1_"1.tif" "exists"                           # skip output files if already created
        echo "Converting " $basename1"_1.tif"                    # give a little feedback
        gdal_translate -b 1 $name $basename1"_1.tif"             # use gdal translate to extract just band 1

        if [ $? -lt 1 ]                                          # if error status is < 1 (0), then remove the original
            echo "Conversion a success."
            echo "Removing original file."
            rm $name
            echo "mehmeh.  try again."


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.