【问题标题】:I get "syntax error near unexpected token `done' " when I use while loop in bash当我在 bash 中使用 while 循环时,出现“意外标记‘完成’附近的语法错误”
【发布时间】:2017-10-18 06:44:20
【问题描述】:

我有一个文件,它逐行填充流式传输方式。我需要通过删除文件中最旧的记录来减少文件的体积。 我想计算行数,如果行数超过 100,则删除最旧的行。但是我收到以下错误:

./1.sh: line 18: syntax error near unexpected token `done'
./1.sh: line 18: `done'

这是我的代码:

#!/bin/bash
FILE="11.txt"
linenum=0

while true; do

#Count number of lines
linenum=`cat "$FILE" | wc -l`

while [ $linenum -gt 100 ] do

#Delete the head of file (oldest)
sed -i 1,1d "$FILE"

#Count number of lines
linenum=`cat "$FILE" | wc -l`

done

done

你能帮帮我吗?

【问题讨论】:

  • 这不安全。 sed -i(有效地)复制输入文件,然后用修改后的副本替换原始文件。如果在sed 处理副本时写入原始文件,则这些更改将丢失。
  • @chepner:谢谢你提到这个,你有什么想法吗?
  • 无论是写入文件的内容都需要负责修剪它。
  • @chepner:这行不通!当我将它应用于流文件时,它无法工作! :((

标签: bash file while-loop


【解决方案1】:

while 的条件和do 之间需要换行符或;

while [ $linenum -gt 100 ]; do

    #Delete the head of file (oldest)
    sed -i 1,1d "$FILE"

    #Count number of lines
    linenum=$(wc -l "$FILE")

done

我还正确缩进了代码,将子shell `...` 表示法更改为更现代的$(...),并删除了cat 的多余使用。

【讨论】:

    【解决方案2】:

    你错过了下一行的分号

    while [ $linenum -gt 100 ] do
    

    应该是

    while [ $linenum -gt 100 ] ; do
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-10
      • 2015-01-01
      • 2018-07-03
      • 1970-01-01
      • 2020-06-10
      • 2011-08-02
      • 1970-01-01
      • 2014-02-26
      相关资源
      最近更新 更多