peter.slizik
peter.slizik

Reputation: 2076

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)

Upvotes: 3

Views: 2077

Answers (1)

Anthony Geoghegan
Anthony Geoghegan

Reputation: 12013

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.

Upvotes: 6

Related Questions