user7581013
user7581013

Reputation:

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?

Upvotes: 1

Views: 485

Answers (2)

Krishnom
Krishnom

Reputation: 1446

You missed the semicolon at below line

while [ $linenum -gt 100 ] do

should be

while [ $linenum -gt 100 ] ; do

Hope this helps.

Upvotes: 0

Aaron
Aaron

Reputation: 24812

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.

Upvotes: 4

Related Questions