How to Fix "command not found" Error in Bash Variable Assignments


How can we fix the command not found error when assigning a variable in a bash script?

TLDR: remove the spaces around the = sign. Read ahead if you’re curious!

Suppose we have a bash script script.sh that attempts to assign a variable and echo it to the terminal.

#!/bin/bash
foo = bar
echo $foo

However, assigning foo to the string "bar" in this way will produce the error:

./script.sh: line 2: foo: command not found

The secret is that this command is not a variable assignment.

Troubleshooting the command not found error

If we move the equals sign = around, we’ll notice some strange errors.

Either of the following variable assignments will produce a foo: command not found error.

foo = "bar"
foo ="bar"

Moving the equals sign over again will produce a bar: command not found error.

foo= "bar"

Remove spaces around the = sign

As we can tell, there shouldn’t be any spaces around the = sign.

There are three possible ways to make this mistake:

1. Spaces around the = sign

Here, the bash script tries to run a command called foo with 2 arguments (= and bar).

foo = "bar"

This command is equivalent to foo "=" "bar".

2. Space before the = sign

Here, the bash script tries to run a command called foo with 1 argument (=bar).

foo ="bar"

This command is equivalent to foo "=bar".

3. Space after the = sign

foo= "bar"

The bash script assigns foo to an empty string and tries to run a command called bar

This command is equivalent to foo="" bar.

This issue is also relevant when we try to include dashes - in the variable name, so we’ll need to remove the dash if we encounter that situation.