swhite
swhite

Reputation: 497

Set Bash Variable to another causes operand error

I've looked through several answers on stack overflow relating to setting a bash variable resulting in a "syntax error: operand expected" and tried some suggestions without success. I'm new to bash and Linux in general so I hope someone can help.

Basically my coworker wants me to run the following in terminal:

export TOPDIR=/home/user/folder/subfolder
export TOP=$TOPDIR

However I get an error on the second line:

bash: export: /home/user/folder/subfolder: syntax error: operand expected (error token is "/home/user/folder/subfolder")

I have tried changing the line to some variations such as

export TOP=${TOPDIR}

and

export TOP="${TOPDIR}"

without success.

Any suggestions or help on what I am doing wrong would be appreciated.

NOTE: I tried setting TOP to the file location directly without success. If I echo $TOP I get 0 returned.

echo $BASH_VERSION = 4.2.46(2) - release

Upvotes: 1

Views: 498

Answers (1)

melpomene
melpomene

Reputation: 85897

The problem is that TOP has been declared as an integer (using declare -i TOP or equivalent).

From the declare documentation:

-i

The variable is to be treated as an integer; arithmetic evaluation (see Shell Arithmetic) is performed when the variable is assigned a value.

That's why

export TOP=$TOPDIR

tries to evaluate /home/user/folder/subfolder as an arithmetic expression and fails (because it's a syntax error).

Possible ways to proceed:

  1. Find out where and why TOP was declared as an integer1 and (if it was not intended) remove it.
  2. Use a different variable name.
  3. Use declare +i TOP to remove the integer attribute from TOP.

1 Possible culprit: The gluster bash completion script declares TOP as an integer and leaks it into the global environment. There's a patch that fixes the problem (or rather moves it; it just renames TOP to GLUSTER_TOP).

Upvotes: 4

Related Questions