1

I have the following test.sh script:

#!/bin/bash
foo=0
bar=foo;
${bar}=1
echo $foo;

Output:

./test.sh: line 4: foo=1: command not found
0

Why the "command not found" error? How to change script to "echo $foo" outputs 1?

Danilo
  • 382
  • 7
  • 23

2 Answers2

2

That's not the way to do indirection unfortunately. To do what you want you could use printf like so

printf -v "$bar" "1"

which will store the value printed (here 1 in the variable name given as an argument to -v which when $bar expands here will be foo

Also, you could use declare like

declare "$bar"=1

which will do variable substitution before executing the declare command.

In your attempt the order of bash processing is biting you. Before variable expansion is done the line is split into commands. A command can include variable assignments, however, at that point you do not have a variable assignment of the form name=value so that part of the command is not treated as an assignment. After that, variable expansion is done and it becomes foo=1 but by then we're done deciding if it's an assignment or not, so just because it now looks like one doesn't mean it gets treated as such.

Since it was not processed as a variable assignment, it must not be treated as a command. You don't have a command named foo=1 in your path, so you get the error of command not found.

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
1

You need to use the eval function, like

#!/bin/bash
foo=0
bar=foo;
eval "${bar}=1"
echo $foo;

The ${bar}=1 will first go through the substitution process so it becomes foo=1, and then the eval will evaluate that in context of your shell

Soren
  • 14,402
  • 4
  • 41
  • 67