Bash while循环`done'语法错误意外令牌

时间:2015-07-23 19:40:58

标签: linux bash shell while-loop virtualbox

在VirtualBox上学习Linux中的bash脚本。

我正在编写一个脚本,如果您决定不覆盖现有文件,则使用while循环来询问要写入的文本文件。

这是我的代码:

#!/bin/bash

bool="true"
counter="true"
while [ "${bool}" == "true" ] ; do
    bool="false"
    if [ "${counter}" == "true" ] ; then
    if [ $# -eq 1 ] ; then
        ff=$1
    fi
    else
    read -p "Enter the .txt file you would like to write to: " ff
    fi

    txt=".txt"
    if [[ $ff != *$txt* ]] ; then
    echo $ff
    ff="$ff$txt"
    echo $ff
    fi

    if [ -w $ff ] ; then
    var="true"
    while [ "${var}" == "true" ] ; do
        var="false"
        read -p "${ff} already exists. Do you want to overwrite it? y/n: " yorn
        if [ $yorn == "y" ] ; then
        echo "'$ff' is being overwitten"
        elif [ $yorn == "n" ] ; then
        echo "Let's try this again..."
        bool="true"     
        else
        echo "You entered a command other than y or n."
        var="true"
        fi
    done
    else
    echo "'$ff' has been created"
    fi

    counter="false"
done

echo "Writing to ${ff}..."
echo "${ff}" > $ff
echo "" >> $ff

declare -a alphabet=("a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z")
echo ${alphabet[@]}
letters=${#alphabet[@]}
echo "There are ${letters} letters in the alphabet"
loops=$((letters*letters*letters))
echo "The script loops ${loops} times"

start=$(date +%s.%N)
for x in "${alphabet[@]}"
do
    x=$x$x
    for y in "${alphabet[@]}"
    do
    y=$y$y
    for z in "${alphabet[@]}"
    do
        z=$z$z
        xyz=$x$y$z
        grep $xyz /usr/share/dict/words >> $ff
    done
    done
done
end=$(date +%s.%N)
elapsed=$(echo "$end - $start" | bc -l)
echo "The search took ${elapsed} seconds."

sleep 10s
emacs $ff

exit 0

这是我完成while循环的错误:

ubuntu@ubuntu-VirtualBox:~/scripts$ ./script.sh abc
./script.sh: line 35: syntax error near unexpected token `done'
./script.sh: line 35: `done'

这里有什么问题?

1 个答案:

答案 0 :(得分:1)

您有两个问题:

1)你需要一个空间。作为一般性建议,最好在bash中使用shell内置[[ ... ]]而不是测试[ ... ]

if [ "${counter}" == "true" ] ; then
                           ^

2)你没有关闭if" fi"这里。

  elif [ $yorn == "n" ] ; then
        echo "Let's try this again..."
        bool=true
  fi # <--- Closing "fi" here

如果您缩进代码,可以更快地发现这类错误。