【问题标题】:Shell script “for” loop syntaxShell 脚本“for”循环语法
【发布时间】:2019-03-15 13:04:12
【问题描述】:

我已经完成了以下工作:

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

【问题讨论】:

  • 它是 bash 脚本吗?
  • UPS...对不起!是的,它是一个 bash 脚本“#!/bin/bash”
  • 会不会和this有关?
  • 会不会是你的脚本有 windows 行尾 (CR LF)?
  • 顺便说一句,无论如何,这是遍历文件列表的错误方法;见Bash FAQ 001

标签: bash shell loops for-loop


【解决方案1】:

不解析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

【讨论】:

  • 但是您仍然需要处理 CRLF 行尾。
猜你喜欢
  • 2011-08-03
  • 2010-12-19
  • 2018-05-16
  • 2022-05-17
  • 2017-04-17
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
相关资源
最近更新 更多