Louis D
Louis D

Reputation: 33

function in loop corrupts every other iteration

I made a short bash program to download podcasts and retrieve only last 20 seconds. Strange thing is it fails downloading every other iteration. There seems to be a problem with the function trim_nsec, because when I get rid of it in the loop, all the rest correctly works.

Edit : addition of double quotes, which doesn't solve the problem

<!-- language: lang-bash -->
#!/bin/bash

# Get podcast list
wget -O feed http://www.rtl.fr/podcast/on-n-est-pas-forcement-d-accord.xml

function trim_nsec () {
    # arguments : 1 : mp3file - 2 : duration - 3 : outputfile
    duration=$(ffprobe -i "${1}" -show_entries format=duration -v quiet -of csv="p=0")
    nth_second=$(echo "${duration} - ${2}"|bc)
    ffmpeg -i "${1}" -ss "${nth_second}" "${3}"
}

cpt=1

# let's work only on the 4th first files
grep -Po 'http[^<]*.mp3' feed|grep admedia| head -n 4 > list

cat list | while read i
do
    year=$(echo "$i" | cut -d"/" -f6)
    day=$(echo "$i" | cut -d"/" -f7)
    fullname=$(echo "$i" | awk -F"/" '{print $NF}')
    fullnameend=$(echo "$fullname" |sed -e 's/\.mp3$/_end\.mp3/')
    new_name=$(echo "$year"_"$day"_"$fullnameend")

    # let's download
    wget -O "$fullname" "$i"
    # let's trim last 20 sec
    trim_nsec "$fullname" 20 "$new_name"
    echo "$cpt file processed"
    #delete orig. file :
    rm "$fullname"
    ((cpt++)) 
done

Any idea ?

Upvotes: 0

Views: 49

Answers (1)

ewcz
ewcz

Reputation: 13087

The problem is most likely due to the fact that on errors, ffmpeg will try to get an input from user which will consume the input provided by cat list. See a similar question here or here. To prevent trim_nsec from consuming the input from cat list, you could do:

cat list | while read i
do
    year=$(echo "$i" | cut -d"/" -f6)
    day=$(echo "$i" | cut -d"/" -f7)
    fullname=$(echo "$i" | awk -F"/" '{print $NF}')
    fullnameend=$(echo "$fullname" |sed -e 's/\.mp3$/_end\.mp3/')
    new_name=$(echo "$year"_"$day"_"$fullnameend")

    # let's download
    wget -c -O "$fullname" "$i"

    # let's trim last 20 sec
    trim_nsec "$fullname" 20 "$new_name" <&3
    echo "$cpt file processed"
    #delete orig. file :
    #rm "$fullname"
    ((cpt++))

done 3<&1

Upvotes: 1

Related Questions