繁体   English   中英

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

[英]Bash 'source': syntax error near unexpected token `then'

我有一个简单的bash脚本:

#!/bin/bash

if [ -n "abcd" ]; then
    echo "a non-empty string"
else
    echo "an empty string"
fi

脚本运行正常:

$ bash test.sh
non-empty string

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

$ source test.sh
bash: ./test.sh: line 3: syntax error near unexpected token `then'
bash: ./test.sh: line 3: `if [ -n "abcd" ]; then

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

$ bash --version
GNU bash, version 4.3.42(1)-release (x86_64-redhat-linux-gnu)

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

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

if is aliased to <some command>
if is a shell keyword

然后, unalias if要删除别名,则可以通过运行unalias if来解决此问题。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM