递归循环遍历文件夹

递归循环遍历文件夹

我正在尝试运行一个脚本,该脚本将解压 rar 文件并添加一个文件以将该文件标记为“已处理”,但它会抛出目录未找到之类的异常,我不确定原因。

#!/bin/bash

function recursive {
    if [ -d "$1" ]; then
        for dir in "$1"; do
            if [ -f "$dir"*rar ]; then
                for file in $dir*.rar; do
                    echo $file

                    if [ ! -f "$dir$file.processed" ]; then                                
                       unrar e "$dir$file.rar" "$dir"
                       touch "$dir$file.processed"
                    fi
                done
            fi

            echo $dir

            subs= find $dir -maxdepth 1 -type d=
            if [ "$subs" != "0" ] && [ "$subs" != "No such file or directory" ]; then
                recursive "$dir*/"
            fi
        done
    fi
}

recursive /home/user/Complete/*/

答案1

该脚本基于您的回答,但它使用find而不是手动浏览文件系统。

#!/bin/bash

unrar_if_needed()(
    file="$1"
    dir="$(dirname "$file")" # Extract dir name from file path.
    echo "Found: $file"
    if [[ -f "$file".processed ]]; then # Double brackets are better.
        echo "    Already unrared."
    else
        echo -n "    Unraring... "
        if unrar -inul e "$file" "$dir"; then # This if-statement is not necessary, but a nice touch.
            touch "$file".processed
            echo "Done."
        fi
    fi
)

export -f unrar_if_needed

if [[ "$1" ]]; then
    dir="$1"
else
    dir=.
fi

echo "Looking in: $dir"
find "$dir" -iname "*.rar" -exec bash -c 'unrar_if_needed {}' \; # find runs the custom function.

输出应如下所示:

$ script.sh somedir
Looking in: somedir
Found: ./somedir/file1.rar
    Unraring... Done.
Found: ./somedir/file2.rar
    Already unrared.

答案2

#!/bin/bash

function recursive {
    echo "$1"
    for dir in "$1"*/; do
        if [ -d "$dir" ]; then
            echo "Reading Directory for rars: $dir"
            for file in "$dir"*.rar; do
                echo "Found Rar: $file"
                if [ ! -f "$dir"processed ] && [ ! -f "$file".processed ]; then
                    echo "File not unrared. Unraring File."                                
                    unrar e "$file" "$dir"
                    touch "$dir"processed
                    echo "File Processed."
                else
                    echo "File already Unrared."
                fi
            done
            echo "......Going Deeper......"
            recursive "$dir"
        fi
    done
}

recursive /home/user/Complete/

相关内容