寻找我的bash脚本的一些帮助。我正在尝试编写此shell脚本来执行以下操作:
在名为的目录中查找文件:
server1-date.done
server2-date.done
server3-date.done
...
server10-date.done
打印到listA
listB
listA
的计数为10
(基本上找到了10个.done
个文件),那么
继续将listB
中的文件移动到新目录listB
移动文件后,删除名称相似的旧目录(server1-date
,server2-date
,...)和.done文件。到目前为止,我已经开始了这项工作。我无法获得if
部分工作的条件。我认为我没有正确编码。任何代码建议,改进等将不胜感激。感谢。
#Directories
GZDIR=/mydumps/mytest
FINALDIR=/mydumps/mytest/final
FLGDIR=/backup/mytest/flags
export GZDIR FINALDIR FLGDIR
#lists
FLGLIST="/mydumps/mytest/lists/userflgs.lst"
GZLIST="/mydumps/mytest/lists/gzfiles.lst"
export FLGLIST GZLIST
#Find files
find $FLGDIR -name \*.done -print > $FLGLIST
find $GZDIR -name \*.gz -print > $GZLIST
#Get need all (10) flags found before we do the move
FLG_VAL =`cat $FLGLIST | wc -l`
export $FLG_VAL
if [ "$FLG_VAL" = "10" ]; then
for FILE in $GZLIST
do
echo "mv $GZLIST $FINALDIR" 2>&1
for FLAG in $FLGLIST
do
echo "rmdir -f $FLAG" 2>&1
done
done
else
echo "Cannot move file" 2>&1
exit 0
fi
答案 0 :(得分:2)
首先,我真的建议您作为默认方法始终test for exceptions,并且除非必要,否则不要在测试中包含“正常”情况。
...
FLG_VAL=`wc -l < $FLGLIST` # no need for cat, and no space before '='
export $FLG_VAL
if [ "$FLG_VAL" != "10" ]; then
echo "Cannot move file" 2>&1
exit 0
fi
for FILE in $GZLIST
do
echo "mv $GZLIST $FINALDIR" 2>&1
for FLAG in $FLGLIST
do
echo "rmdir -f $FLAG" 2>&1
done
done
现在看看错误检查被提取出来并且自立的代码是多么容易阅读?
答案 1 :(得分:2)
我不知道这是否有效,但它会解决所有明显的问题:
#!/bin/sh
#Directories
GZDIR=/mydumps/mytest
FINALDIR=/mydumps/mytest/final
FLGDIR=/backup/mytest/flags
export GZDIR FINALDIR FLGDIR
#lists
FLGLIST="/mydumps/mytest/lists/userflgs.lst"
GZLIST="/mydumps/mytest/lists/gzfiles.lst"
#Find files
find "$FLGDIR" -name '*.done' -print > "$FLGLIST"
find "$GZDIR" -name '*.gz' -print > "$GZLIST"
#Get need all (10) flags found before we do the move
FLG_VAL=$(wc -l <"$FLGLIST") # Always prefer $( ... ) to backticks.
if [ "$FLG_VAL" -ge 10 ]; then
for FILE in $(cat "$GZLIST")
do
echo "mv $FILE $FINALDIR" 2>&1
done
for FLAG in $(cat "$FLGLIST")
do
echo "rmdir -f $FLAG" 2>&1
done
else
echo "Cannot move file" 2>&1
exit 0
fi
答案 2 :(得分:1)
FLG_VAL =`cat $FLGLIST | wc -l`
应该是:
FLG_VAL=`cat $FLGLIST | wc -l`