循环的Bash脚本运行良好,但在使用源代码运行时出现语法错误



我有下面的bash脚本

#!/bin/bash
for i in 4 5 6; do
  echo $i
done    

当我运行脚本时,它运行良好:

$ ./testbash 
4
5
6

当我源代码相同的脚本时,我得到以下语法错误

$ source testbash
bash: /home/nick/bin/testbash: line 5: syntax error: unexpected end of file

在获取bash文件时是否禁止某些命令?我使用的是GNUbash,版本4.1.2

这是脚本的六进制转储

$hexdump-C testbash

00000000  23 21 2f 62 69 6e 2f 62  61 73 68 0a 66 6f 72 20  |#!/bin/bash.for |
00000010  69 20 69 6e 20 34 20 35  20 36 3b 20 64 6f 0a 20  |i in 4 5 6; do. |
00000020  20 65 63 68 6f 20 24 69  0a 64 6f 6e 65 0a        | echo $i.done.|
0000002e

源代码和执行会产生不同结果的原因有很多,但会出现新的bash语法错误的原因要少得多。

运行env -i bash --norc以获得一个干净的shell,这样您就可以检查它是否与当前shell相关。

如果source在这个干净的shell中运行良好,请将以下命令的输出与失败的shell进行比较:

  1. alias(如果您替换或引入类似done的关键字)
  2. shopt(如果您修改了extglob等语法更改选项)
  3. echo $BASH_VERSION(以防交互式rc文件最终在不同的shell中执行)

最新更新