2017-06-14 151 views
0

我下面的文件夹stucrtreshell脚本文件夹结构中循环和EXCUTE shell脚本

在/ var /数据/ 2017年/ 01/$天/文件

我想EXCUTE shell脚本为循环中的所有月份/天,运行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 

我不知道有关的逻辑在这里,我错过了文件列表我怎么才能得到它

这里任何建议

+0

你是什么意思“错过了文件列表”,什么是不正确的工作? – dood

+0

我的意思是当我在每天循环生病有多个文件在那里运行shell脚本aginst每个文件,我怎么可以将文件添加到循环一旦完成从第1天我移动到第2天等 – Jecki

回答

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 
+0

看起来不错,如果我想将月份本身作为var?所以它会是月份{1..12}? – Jecki

+0

顺便说一句,你不需要'[[-e $ file]]'测试。 '$ file'存在,因为它是'$ dir_proc/$ month/$ day /“'中'for file的输出的一部分。除非在短时间内它被删除了。即使对月份和日期的测试也是多余的,除了保存几个处理器周期来检查不存在的文件目录。 – Deathgrip

+1

@Deathgrip,这是为了处理没有文件的情况:glob不会扩展,默认情况下'file ='dir/*''也许'shopt -s nullglob'也可以使用 –

1

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

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

或与Processing...线(与GNU FIND):

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

如果你只想在树的一些子目录运行,你需要使用-path-name-prune限制匹配。