简体   繁体   中英

I get “syntax error near unexpected token `done' ” when I use while loop in bash

I have a file which filled in streaming way line by line. I need to decrease the volume of the file by deleting the oldest record in it. I would like to count the number of lines and if the number of lines exceed than 100 then delete the oldest lines. However I got the following error:

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

Here is my code:

#!/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

Can you please help me?

You need a linefeed or a ; between the while 's condition and the 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

I also indented the code properly, changed the subshell `...` notation to the more modern $(...) and removed a redundant use of cat .

You missed the semicolon at below line

while [ $linenum -gt 100 ] do

should be

while [ $linenum -gt 100 ] ; do

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM