问题
I understand similar questions to this been asked in SO multiple times. However, I couldn't find any usual suspects here.
#!/bin/bash
myvar="test"
if [ "$myvar" == "test" ]
then
echo "Test mode"
fi
Spent quite some time on it. Can anyone advice what am I missing?
I am able to execute the script, but couldn't source the same.
error while source bash: test.sh: line 7: syntax error: unexpected end of file
$ which bash
/bin/bash
$ bash --version
3.2.57(1)
I am able to get the same working on my another Mac. So, it's pretty much something wrong on my Mac, but couldn't figure out what it is. Also, not only the above-mentioned script, any script with "if" condition I couldn't source. Tried different examples mentioned here, same syntax error.
edit1:
$ file test.sh
test.sh: Bourne-Again shell script text executable, ASCII text
edit2:
$ hexdump -C test.sh
00000000 23 21 2f 62 69 6e 2f 62 61 73 68 0a 6d 79 76 61 |#!/bin/bash.myva|
00000010 72 3d 22 74 65 73 74 22 0a 69 66 20 5b 20 22 24 |r="test".if [ "$|
00000020 6d 79 76 61 72 22 20 3d 3d 20 22 74 65 73 74 22 |myvar" == "test"|
00000030 20 5d 0a 74 68 65 6e 0a 65 63 68 6f 20 22 54 65 | ].then.echo "Te|
00000040 73 74 20 6d 6f 64 65 22 0a 66 69 0a |st mode".fi.|
0000004c
回答1:
Check for newline character differences or encoding pages. if it something as simple as this and there is a mac involved, always check that first
回答2:
As other users already stated, you can check if newline is LF because CRLF will fail in linux. if you convert the script it should be fixed. you can install a tool which can convert CRLF into LF:
dos2unix test.sh
Regarding the sourcing, not sure if this may help you with your issue. assuming the wrapper script which sources test.sh is not called from bash...
#!/bin/sh
. ./test.sh
...the if statement will fail, because bourne shell does not support '==' but if you change it to...
#!/bin/bash
myvar="test"
if [ "$myvar" = "test" ]
...the script will sourced without errors. Please note it depends on how the script is sourced, the shebang might be ignored
回答3:
Okay finally, found the issue.
I removed my .bashrc file and its working fine. Looks like something in .bashrc was messing it.
$ source test.sh
Test mode
Thanks, everyone appreciate it.
来源:https://stackoverflow.com/questions/55720897/unable-to-source-a-simple-bash-script