[英]Bash 'source': syntax error near unexpected token `then'
I have a simple bash script: 我有一个简单的bash脚本:
#!/bin/bash
if [ -n "abcd" ]; then
echo "a non-empty string"
else
echo "an empty string"
fi
The script runs fine: 脚本运行正常:
$ bash test.sh
non-empty string
But when I try to source it, a strange error message is produced: 但是,当我尝试它源 ,产生一个奇怪的错误信息:
$ source test.sh
bash: ./test.sh: line 3: syntax error near unexpected token `then'
bash: ./test.sh: line 3: `if [ -n "abcd" ]; then
Any advice welcome. 欢迎任何建议。 The problem appears with any script containing the
if
command, including Fedora's /etc/bashrc
and my other scripts. 任何包含
if
命令的脚本都会出现问题,包括Fedora的/etc/bashrc
和我的其他脚本。
$ bash --version
GNU bash, version 4.3.42(1)-release (x86_64-redhat-linux-gnu)
Such an error would occur if a command includes the then
shell keyword without a corresponding if
keyword. 如果命令包含
then
shell关键字而没有相应的if
关键字,则会发生此类错误。
If the word if
was used to define an alias, the alias would be expanded before Bash parses your commands, resulting in such an error. 如果单词
if
用于定义别名,则在Bash解析命令之前将扩展别名,从而导致此类错误。 This can be checked by running type -a if
. 这可以通过运行
type -a if
来检查。 If it has been aliased, you'll see output similar to 如果它已被别名,您将看到类似的输出
if is aliased to <some command>
if is a shell keyword
The problem can then be resolved by running unalias if
to remove the alias. 然后,
unalias if
要删除别名,则可以通过运行unalias if
来解决此问题。
When running bash test.sh
, the new shell is non-interactive and by default, Bash only expands aliases for interactive shells. 运行
bash test.sh
,新shell是非交互式的,默认情况下,Bash只扩展交互式shell的别名。 Running source test.sh
means the commands in the file were interpreted in your current (interactive) shell and the problematic alias was expanded. 运行
source test.sh
意味着文件中的命令在当前(交互式)shell中进行了解释,并且扩展了有问题的别名。
For future reference, if there are problems in an interactive shell, but not in non-interactive shells, it's worth running alias
to check which aliases have been defined. 为了将来参考,如果交互式shell中存在问题,但非交互式shell中存在问题,则需要运行
alias
来检查已定义的别名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.