“if”语句导致 bash 脚本中意外标记“done”附近出现语法错误

“if”语句导致 bash 脚本中意外标记“done”附近出现语法错误

我正在尝试编写一个脚本,每 5 次迭代在循环中创建一个新文件:

#!/bin/bash
counter=1
timestamp="$(($(date +%s%N)/1000000))"
fileName="file"$timestamp".txt"
echo $fileName
while [ $counter -le 5 ]
do
        echo $counter
        ((counter++))
        timestamp="$(($(date +%s%N)/1000000))"
        echo $counter
        if [ $counter == 5 ]
        then
            echo "Creating new file"
            fileName="file"$timestamp".txt"
            counter=1
        echo "${timestamp}" >> $fileName
        sleep 2s
        echo $counter
done

该脚本返回错误:

file1561151901170.txt
ruunn.sh: line 20: syntax error near unexpected token `done'
ruunn.sh: line 20: `done'

如果我删除该if条款:

#!/bin/bash
counter=1
timestamp="$(($(date +%s%N)/1000000))"
fileName="file"$timestamp".txt"
echo $fileName
while [ $counter -le 5 ]
do
        echo $counter
        ((counter++))
        timestamp="$(($(date +%s%N)/1000000))"
        echo $counter
        echo "${timestamp}" >> $fileName
        sleep 2s
        echo $counter
done

不会引发错误并且输出符合预期:

file1561152065603.txt
1
2
2
2
3
3
3
4
4
4
5
5
5
6
6

那么看来问题出在该if条款上?

如何修改我的脚本以允许将该if子句包含在文件创建过程中?

答案1

if错过了它的结束fi

相关内容