[英]FOR loop nested in WHILE in bash/shell
I want to get proper output from FOR loop inside WHILE. 我想从WHILE内的FOR循环中获取正确的输出。 When i'm using command like this all is OK: 当我使用这样的命令时,一切正常:
for i in `find ./ -name "*.processed" -mtime +0`; do echo "$i is COOL"; done;
Output:
1.processed is COOL
2.processed is COOL ...
But, when i'm using this into bash/shell script, find put a list of all files with proper mask into variable (not one by one). 但是,当我在bash / shell脚本中使用它时,找到将带有适当掩码的所有文件的列表放入变量中(而不是一个一个)。 Note, redirect "echo $i is COOL" to "wc -l" returns number of all files, damn. 注意,将“ echo $ i is COOL”重定向到“ wc -l”将返回所有文件的数量,该死。 See following: Entries of confif file like: 请参阅以下内容:confif文件条目,例如:
/export/home/.../ProcessedDumps;*.processed
All paths are full paths. 所有路径都是完整路径。
#!/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
Is bash provides nested loops with different kinds (inner FOR, outer WHILE). bash提供了不同种类的嵌套循环(内部FOR,外部WHILE)。 Have any ideas? 有什么想法吗?
Rather than setting IFS
globally, which is interfering with your for
loop, set it locally for the read
in the while loop: 而不是全局设置会干扰for
循环的IFS
,而是在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
the problem seems to be with the shell expansion, the follow excerpt worked as expected in my test here 问题似乎与外壳扩展有关,以下摘录按我在此处测试中的预期进行了工作
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
EDIT : the IFS also has an important role if the filename has whitespaces, as noted by hobbs, in this case, one can use 编辑 :如果文件名具有空格(如hobbs所述),则IFS也起着重要作用,在这种情况下,可以使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.