Bash – for loop in bash function

bashfunctionwildcards

I recently wrote the following bash function:

makeaudiobook () {
count=1
almbumartist=$2
for f in $1; do
        preprocess $f > $f-preprocessed
        text2wave $f-preprocessed -o $f.wav
        lame -b 16 --tt $f --ta $albumartist --tl $albumartist --tn $count $f.wav $f.mp3
        rm -rf $f.wav $f-preprocessed
        count=$(($count+1))
done
}

It does not work as expected. It does not iterate over all of the files that fit the glob expression I specify in $1. As a one-liner, this would work. An in fact, I made this into a function because I was tired of writing it out as a one-liner. But as a bash function, it doesn't work. So what do I need to do to make it work?

I want to be able to call it on things like the output of split, like,

me@localhost$~ makeaudiobook x?? haskell

…where x?? matches xaa, xab, xac, etc. Like I said, as a one-liner this is fine. So what do I need to do to pass this glob expression to $1?

Best Answer

x?? is expanded at the time of function call. So your function is already called with xaa xab xac... .

The simplest way would be to change the ordering of your parameters:

makeaudiobook () {
count=1
almbumartist=$1
shift
for f in "$@"; do
        preprocess "$f" > "$f"-preprocessed
        text2wave "$f"-preprocessed -o "$f".wav
        lame -b 16 --tt "$f" --ta "$albumartist" --tl "$albumartist" --tn "$count" "$f".wav "$f".mp3
        rm -rf "$f".wav "$f"-preprocessed
        count=$(($count+1))
done
}

(look how I put " around every variable - this is to prevent bad things from happening if you have whitespace in your file names, what often happens with audio files)

and call it with makeaudiobook haskell x??, i. e. with rotated arguments.