views:

70

answers:

4

Since i have some video courses in my laptop. I now want to calculate the total time of every course. So i write a simple script with bash.

It succeeds for file/dir without space. But for dir/files with space, it goes wrong. I have tried to set IFS to something else, it doesn't work either. Well, there also some bugs in it.

#!/bin/bash

## Usage: calTime.sh dir

#set -e

getTime(){
    message=$($VIDEOTOOL $OPTION $FILE | grep "Duration")
    if [ $? -eq 0 ]
    then
        local time=$(echo $message | cut -d',' -f1 | cut -d' ' -f5)
        echo -e $time "\t" $FILE 
        #second=$(($second + $time))
        let second+=$time
    fi
} 2>/tmp/error

process(){
    if [ -f $FILE ]
    then
        getTime
    elif [ -d $FILE ]
    then
        cd $FILE
        for i in $(ls);
        do
            local FILE=$i
            process
        done
    fi
}

#################
#### main #######
#################

VIDEOTOOL=/usr/bin/avidemux2_cli
OPTION="--nogui --info --load"
second=0

list=${@-./}

for FILE in $list
do
    process
done

echo $second
+1  A: 

Stick your variables in quotes.

tc.
Use double quotes.
Sjoerd
still doesn't work ;-(
stupid.kid
well, i use -x flag to debug and find the problem in logic.there should be a cd .. to change back to parent dir.
stupid.kid
+1  A: 
Sjoerd
+1  A: 

You have to protect your variable $FILE with double quote like this "$FILE"

Dimitri
+1  A: 

Your problem appears to be with the line:

for i in $(ls);

Try this instead:

for i in *

Plus, as others have said, any time you have a variable that contains a filename, it should be in double quotes. For example:

message=$($VIDEOTOOL $OPTION "$FILE" | grep "Duration")
Dennis Williamson