Fri Aug 21 20:49:29 PDT 2015

Recursion in Bash

Here is a short script which goes through a directory structure and operates on mp3 or MP3 files. It uses standard bash methods - and I am posting it here in case you are interested - you can achieve the same effect with:

find . -name "*.[mM][pP]3" -print

...but this script is more fun - and substantially slower - giving you time to think about other things - which is often useful. The script prints out the names of the files it encounters - you could have it do something else - like report checksums (cksum) or modification times (ls -lt). The necessary lines for these operations have been commented out in the script. You can use this script as a template to carry out other file based scripted operations. Also note that it won't find files with the following cases in their extensions: mP3 or Mp3.

#!/bin/bash
scandir () {
for item in *
do
  if [ -f "$item" ] ; then
    curdir=`pwd`
    nfile=`expr $nfile + 1`
    EXT=`echo "$item" | rev | cut -c 1-3 | rev`
    if [ $EXT = "mp3" -o $EXT = "MP3" ]
    then
      echo "$curdir"/"$item" | cut -c${ld1}-
    fi
  elif [ -d "$item" ] ; then
    cd "$item"
    scandir
    ndirs=`expr $ndirs + 1`
    cd ..
  fi
done
}
startdir=`pwd`
ld1=`echo $startdir | wc -c`
ld1=`expr $ld1 + 1`
echo "Initial directory = $startdir"
ndirs=0
nfile=0
scandir
echo "Total directories searched = $ndirs"
echo "Total files = $nfile"

Posted by ZFS | Permanent link | File under: bash