首页 > 解决方案 > Shell 脚本“for”循环语法

问题描述

我已经完成了以下工作:

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' " 有人可以帮忙吗?

标签: bashshellloopsfor-loop

解决方案


无需解析即可执行相同操作的简单逻辑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

推荐阅读