意外令牌'完成'附近的BASH语法错误

use*_*725 20 bash

知道问题可能是什么?

我的代码是:

#!/bin/bash
while :
do
echo "Press [CTRL+C] to stop.."
sleep 1
done
Run Code Online (Sandbox Code Playgroud)

将其保存为.sh并运行bash file.sh

CentOS 6 32位

有什么问题?第一次使用BASH,需要它在一些东西上进行简单的无限循环.

tha*_*guy 30

cat -v file.sh.

您的文件中很可能有回车或无休息空间.cat -v将分别显示为^M和/ M-BM-M-分别显示.它同样会显示您可能已经进入文件的任何其他奇怪字符.

删除Windows换行符

tr -d '\r' < file.sh > fixedfile.sh
Run Code Online (Sandbox Code Playgroud)


Kun*_* B. 11

我在Cygwin上遇到了同样的错误; 我做了以下(其中一个修复):

  1. 转换TABSSPACES
  2. dos2unix.(ba)sh文件


Dav*_* W. 6

您遇到什么错误?

$ bash file.sh
test.sh: line 8: syntax error: unexpected end of file
Run Code Online (Sandbox Code Playgroud)

如果收到该错误,则可能是行尾出现错误。Unix使用<LF>文件末尾,而Windows使用<CR><LF>。该<CR>字符被解释为字符。

您可以od -a test.sh用来查看文件中的不可见字符。

$ od -a test.sh
0000000    #   !   /   b   i   n   /   b   a   s   h  cr  nl   #  sp  cr
0000020   nl   w   h   i   l   e  sp   :  cr  nl   d   o  cr  nl  sp  sp
0000040   sp  sp   e   c   h   o  sp   "   P   r   e   s   s  sp   [   C
0000060    T   R   L   +   C   ]  sp   t   o  sp   s   t   o   p   "  cr
0000100   nl  sp  sp  sp  sp   s   l   e   e   p  sp   1  cr  nl   d   o
0000120    n   e  cr  nl                                                
0000124
Run Code Online (Sandbox Code Playgroud)

sp代表的空间,ht代表选项卡上,cr代表<CR>nl代表<LF>。请注意,所有行都cr以一个nl字符结尾。

您也可以cat -v test.shcat命令中使用-v参数时使用。

如果您dos2unix的文件箱中有文件,则可以使用该命令来修复文件:

$ dos2unix test.sh
Run Code Online (Sandbox Code Playgroud)


cha*_*een 6

有一种方法可以解决这个问题,而不会出现混合换行问题(至少在我的 shell 中,即 GNU bash v4.3.30):

#!/bin/bash
# foo.sh

function foo() {
    echo "I am quoting a thing `$1' inside a function."
}

while [ "$input" != "y" ]; do
    read -p "Hit `y' to continue: " -n 1 input
    echo
done

foo "What could possibly go wrong?"
Run Code Online (Sandbox Code Playgroud)
$ ./foo.sh
./foo.sh: line 11: syntax error near unexpected token `done'
./foo.sh: line 11: `done'
Run Code Online (Sandbox Code Playgroud)

这是因为 bash 在双引号字符串内展开反引号(请参阅有关引用命令替换的 bash 手册),并且在找到匹配的反引号之前,会将任何其他双引号解释为命令替换的一部分:

$ echo "Command substitution happens inside double-quoted strings: `ls`"
Command substitution happens inside double-quoted strings: foo.sh
$ echo "..even with double quotes: `grep -E "^foo|wrong" foo.sh`"
..even with double quotes: foo "What could possibly go wrong?"
Run Code Online (Sandbox Code Playgroud)

您可以通过使用反斜杠转义字符串中的反引号或使用单引号字符串来解决此问题。

我不太确定为什么这只给出一个错误消息,但我认为这与函数定义有关:

#!/bin/bash
# a.sh

function a() {
    echo "Thing's `quoted'"
}
a
while true; do
    echo "Other `quote'"
done
Run Code Online (Sandbox Code Playgroud)
#!/bin/bash
# b.sh

echo "Thing's `quoted'"
while true; do
    echo "Other `quote'"
done
Run Code Online (Sandbox Code Playgroud)
#!/bin/bash
# a.sh

function a() {
    echo "Thing's `quoted'"
}
a
while true; do
    echo "Other `quote'"
done
Run Code Online (Sandbox Code Playgroud)