shell脚本在文件夹结构中循环并执行shell脚本

时间:2017-06-14 08:02:42

标签: bash shell sh

我的文件夹是stucrtre

的/ var /数据/ 2017/01 / $天/文件

我想在所有月/日中执行shell脚本for循环并对所有文件运行shell脚本

DIR_PROC = /var/data/2017/01/$day/$file
for day  in  {1..30}   do
        echo "processing file  $file
        sh  /opt/myscript.sh   /var/data/2017/1/$day/$file

    done

我不确定这里的逻辑我错过了如何获得它的文件

任何建议

2 个答案:

答案 0 :(得分:4)

dir_proc=/var/data/2017/01
# maybe {1..31} because month can have 31 days
for day in {1..30}; do
    # check directory exist || otherwise continue with next day
    [[ -e $dir_proc/$day ]] || continue
    for file in "$dir_proc/$day/"*; do
        # check file exist      || otherwise continue with next file
        [[ -e $file ]] || continue
        # do something with "$file"
    done
done

用几个月编辑:

dir_proc=/var/data/2017
for month in {01..12}; do
    for day in {01..31}; do
        # check directory exist || otherwise continue with next day
        [[ -e $dir_proc/$month/$day ]] || continue
        for file in "$dir_proc/$month/$day/"*; do
            # check file exist      || otherwise continue with next file
            [[ -e $file ]] || continue
            # do something with "$file"
        done
    done
done

或更短,有一个

dir_proc=/var/data/2017
for month_day in {01..12}/{01..31}; do
    # check directory exist || otherwise continue with next day
    [[ -e $dir_proc/${month_day} ]] || continue
    for file in "$dir_proc/${month_day}/"*; do
        # check file exist      || otherwise continue with next file
        [[ -e $file ]] || continue
        # do something with "$file"
    done
done

答案 1 :(得分:1)

如果要为目录结构中的所有文件运行脚本,只需使用find

find /var/data/2017/01 -type f -exec sh /opt/myscript.sh {} \;

或使用Processing...行(使用GNU查找):

find /var/data/2017/01 -type f -printf "Processing %p\n" -exec sh /opt/myscript.sh {} \;

如果您只想在树中的某些子目录上运行,则需要使用-path-name-prune来限制匹配。