FOR循环嵌套在bash / shell中的WHILE中

时间:2013-12-05 07:49:08

标签: bash shell unix loops

我希望在WHILE内部获得FOR循环的正确输出。 当我使用这样的命令时,一切正常:

for i in `find ./ -name "*.processed" -mtime +0`; do echo "$i is COOL"; done; 

Output:
1.processed is COOL
2.processed is COOL ...

但是,当我将它用于bash / shell脚本时,找到一个包含适当掩码的所有文件的列表到变量(不是一个一个)。注意,将“echo $ i is COOL”重定向到“wc -l”会返回所有文件的编号,该死的。见如下: confif文件的条目如:

/export/home/.../ProcessedDumps;*.processed

所有路径都是完整路径。

#!/bin/bash

CONF_FILE=$1
DAYS_OLD=0
counter=0
IFS=";"

if [ "$1" = "-h" -o "$1" = "-help" -o "$#" -ne "1" ]; then
    echo "Just archive your files easy!"
    echo "Usage: `basename $0` /path_to_conf/config.cfg" && echo "Exit!"
    exit 1
fi

echo "#########################"
date '+Date: %Y.%m.%d %T'
echo

while read LOG_DIR MASK
do
    cd $LOG_DIR
    echo "Dir changed to `pwd`"
    echo "Searching with mask \"$MASK\""
    for i in `find . -name "$MASK"`
    do
    echo "$i is COOL"
    echo "test"
    done
done < $CONF_FILE

echo
echo "Total archived files: $counter"

echo
date '+Date: %Y.%m.%d %T'

Output:
1.processed
2.processed
...
n.processed is COOL
test

bash是否提供了不同种类的嵌套循环(内部FOR,外部WHILE)。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

不是全局设置IFS,而是干扰您的for循环,而是在while循环中为read设置本地:

while IFS=';' read LOG_DIR MASK; do
    cd $LOG_DIR
    echo "Dir changed to `pwd`"
    echo "Searching with mask \"$MASK\""
    for i in `find . -name "$MASK"`
    do
        echo "$i is COOL"
        echo "test"
    done
done < $CONF_FILE

答案 1 :(得分:0)

问题似乎是shell扩展,以下摘录在我的测试中按预期工作

echo logdir '"*.c"' | while read LOG_DIR MASK
do
  MASK=${MASK#'"'};
  MASK=${MASK%'"'};
  find -name "$MASK";
  for i in `find -name "$MASK"`; do
    echo "[$i]";
  done
done

编辑:如果文件名有空格,IFS也有重要作用,如hobbs所述,在这种情况下,可以使用

echo logdir '"*.png"' | while read LOG_DIR MASK
do
  MASK=${MASK#'"'};
  MASK=${MASK%'"'};
  SAVEIFS=$IFS
  IFS='!'
  for i in `find -printf '%h/%f!' -name "$MASK"`; do
    ls -l "$i"
  done
  IFS=$SAVEIFS
done