Shell脚本“ for”循环语法

时间:2019-03-15 13:04:12

标签: bash shell loops for-loop

我已经完成了以下工作:

i=0
for log in $(ls -1dt import*.log)
do
((i++))
if [ $i -gt 3 ]; then
rm -rf $log
fi
done

它产生一个:"syntax error near unexpected token 'do' " 有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

无需解析ls即可执行相同操作的简单逻辑-

stat -c "%Y %n" import*.log | # list last modification and filename
  sort -rn                  | # sort reverse numeric on mod time
  while read es fn;           # read the timestamp and the filename
  do if (( ++latest <= 3 ));  # count each file found, for 1st 3
     then continue;           # do nothing, skipping them
     else rm -f "$fn";        # -r for recurse only needed on dir's
     fi;
  done