2017-06-14 149 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限制匹配。