Bash'source':意外令牌附近的语法错误`then'

pet*_*zik 3 bash

我有一个简单的bash脚本:

#!/bin/bash

if [ -n "abcd" ]; then
    echo "a non-empty string"
else
    echo "an empty string"
fi
Run Code Online (Sandbox Code Playgroud)

脚本运行正常:

$ bash test.sh
non-empty string
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试它,产生一个奇怪的错误信息:

$ source test.sh
bash: ./test.sh: line 3: syntax error near unexpected token `then'
bash: ./test.sh: line 3: `if [ -n "abcd" ]; then
Run Code Online (Sandbox Code Playgroud)

欢迎任何建议.任何包含该if命令的脚本都会出现问题,包括Fedora /etc/bashrc和我的其他脚本.

$ bash --version
GNU bash, version 4.3.42(1)-release (x86_64-redhat-linux-gnu)
Run Code Online (Sandbox Code Playgroud)

Ant*_*ica 6

如果命令包含then没有相应if关键字的shell关键字,则会发生此类错误.

如果该单词if用于定义别名,则在Bash解析命令之前会扩展别名,从而导致此类错误.这可以通过运行来检查type -a if.如果它已被别名,您将看到类似的输出

if is aliased to <some command>
if is a shell keyword
Run Code Online (Sandbox Code Playgroud)

然后可以通过运行unalias if删除别名来解决该问题.

运行时bash test.sh,新shell是非交互式的,默认情况下,Bash仅扩展交互式shell的别名.运行source test.sh意味着文件中的命令在当前(交互式)shell中进行了解释,并且扩展了有问题的别名.

为了将来参考,如果交互式shell中存在问题,但非交互式shell中存在问题,则值得运行alias以检查已定义的别名.