1

I have the following bash script

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

When I run the script it works fine:

$ ./testbash 
4
5
6

When I source the same script I get the following syntax error

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

Are certain commands disallowed when sourcing a bash file? I'm using GNU bash, version 4.1.2

Here is the hexdump of the script

$ 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
18
  • What sort of line endings does that file have? (What does file testbash say?) If you run echo >> /home/nick/bin/testbash and then try sourcing it again does it work? Commented Mar 25, 2015 at 22:23
  • Try source ./testbash to avoid it searching your path for old/outdated versions Commented Mar 25, 2015 at 22:27
  • @Etan Reisner I tried dos2linux just in case. No change. file results: testbash: Bourne-Again shell script text executable Commented Mar 25, 2015 at 22:32
  • @that source ./testbash resulted in the same syntax error Commented Mar 25, 2015 at 22:34
  • 1
    @Dijkstra Run env -i bash --norc and try source ./testfile again in that shell. I'm guessing you have an alias called done. Commented Mar 25, 2015 at 23:06

1 Answer 1

1

There are many reasons why sourcing and executing would give different results, but far fewer why you would get a new bash syntax error.

Run env -i bash --norc to get a clean shell so you can check whether it's related to your current shell.

If sourcing works fine in this clean shell, compare the outputs of the following commands with the shell where it fails:

  1. alias (in case you replace or introduce keywords like done)
  2. shopt (in case you modify syntax changing options like extglob)
  3. echo $BASH_VERSION (in case your interactive rc files end up exec'ing a different shell)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.