Bash嵌套循环获得最高

时间:2014-10-03 15:25:11

标签: bash shell

我有一个包含多个文件夹的文件夹,每个文件夹都有一堆mp3文件。

此文件的名称如" 23 - Lecture-1.mp3"

我试图标记mp3,以便按正确的顺序播放音频文件。

所以我需要在每个上提取曲目编号(上例中为23),并将其与所有其他文件进行比较并保持最高。

我的问题是,在通过文件的循环结束后,最高变量不会持久存在,最高值始终为0(我为其初始化的值。)

所以问题是:

如何让bash在循环外保留该值?

find /media/mdisk/Audio -path "*AIFR*" -type d -print0 | while IFS= read -r -d '' folder;  do 
    cd "$folder"; 
    highest=0
    find . -name "*.mp3" -print0 | while IFS= read -r -d '' file;  do 
    basename=`basename "$file"`
    current=$((`echo $basename | cut -d "-" -f1 | sed 's/^0*//'`+ 0));
    highest=$(($highest+0))
    echo "Current is $current"
    if [ "$current" -gt "$highest" ]; then
        highest=$current;
        echo $highest # <--------------- right value here
    fi
    done
    echo "Highest is $highest"; # <----------- value is gone
    echo "";
done

2 个答案:

答案 0 :(得分:2)

这是因为你的管道从findwhile。管道在子壳中创建子壳和变量赋值不会自动移动到父壳。相反,也许可以将find的结果扔到一个变量上,让你的While循环咀嚼掉。

答案 1 :(得分:0)

感谢@kojiro的链接,这是我的解决方案,供将来参考。

find /media/mdisk/Audio -path "*AIFR*" -type d -print0 | while IFS= read -r -d '' folder;  do 
    cd "$folder"; 
    highest=0
    files=`find . -name "*.mp3" -print0`
    while IFS= read -r -d '' file;  do
    basename=`basename "$file"`
    current=$((`echo $basename | cut -d "-" -f1 | sed 's/^0*//'`+ 0));
    highest=$(($highest+0))
    echo "Current is $current"
    if [ "$current" -gt "$highest" ]; then
        highest=$current;
        echo $highest
    fi
    done < <(find . -name "*.mp3" -print0)
    echo "Highest is $highest"; # <--------------- good value now
    echo "";
done
相关问题