【问题标题】:Bash error: syntax error near unexpected token `done'Bash 错误:意外标记“完成”附近的语法错误
【发布时间】:2015-08-14 12:06:35
【问题描述】:

我使用带有 shell 脚本的 ls 编写了一个非常简单的文件浏览器。我使用了一个 while 循环来使脚本永远运行(直到 Ctrl+C),但是 while 循环似乎不起作用。我收到此错误

./fileexplorer: line 5: syntax error near unexpected token `done'
./fileexplorer: line 5: `done'`

我的代码是这样的:

#!/bin/bash
ls -l $1
while :
    browse()
done

function browse()
{
    read file;
    if [ -f $file ]
        if test -e $file
            echo "Starting $file with nano."
            echo "Press a key to open the file."
            pause
            nano $file
    if test -d $file
        ls -l $file
}

【问题讨论】:

标签: bash while-loop


【解决方案1】:

这不是正确的语法,你需要这样的东西:

while CONDITION ; do
    ACTION
done

没有dodone 确实出乎意料。此外,您的if 声明应采用以下形式:

if CONDITION ; then
    ACTION
fi

bash 手册页更详细地显示了正确的形式:

if list; then list; [ elif list; then list; ] ... [ else list; ] fi
while list-1; do list-2; done

请记住,上面显示的是我的首选形式,do/thenwhile/if 在同一行。您也可以取消 ; 并将 do/then 移到下一行,但我认为这会不必要地浪费屏幕空间。

【讨论】:

  • 我修复了它,但它仍然给出同样的错误。我把它改成了“while True; do”。
【解决方案2】:

下面的脚本应该可以工作..

#!/bin/bash

function browse()
{
    read file;
    if [ -f $file ]
    then
        if [ -e $file ]
        then
            echo "Starting $file with nano."
            echo "Press a key to open the file."
            sleep 2
            nano $file
        fi
    fi
    if [ -d $file ]
    then
        ls -l $file
     fi
}

ls -l $1

while true;do
browse
done

【讨论】:

    猜你喜欢
    • 2015-05-10
    • 2015-01-01
    • 2018-07-03
    • 2011-08-02
    • 2014-02-26
    • 2018-12-18
    • 2014-01-20
    • 2015-12-11
    • 2021-07-29
    相关资源
    最近更新 更多