简体   繁体   中英

Bash 'source': syntax error near unexpected token `then'

I have a simple bash script:

#!/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.

$ 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.

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. This can be checked by running 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.

When running bash test.sh , the new shell is non-interactive and by default, Bash only expands aliases for interactive shells. Running source test.sh means the commands in the file were interpreted in your current (interactive) shell and the problematic alias was expanded.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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