Stan Kurilin
Stan Kurilin

Reputation: 15792

Using spaces in bash scripts

I have a script foo.sh

 CMD='export FOO="BAR"'
 $CMD
 echo $FOO

It works as expected

 >./foo.sh 
 "BAR"

Now I want to change FOO variable to BAR BAR. So I get script

 CMD='export FOO="BAR BAR"'
 $CMD
 echo $FOO

When I run it I expect to get "BAR BAR", but I get

 ./foo.sh: line 2: export: `BAR"': not a valid identifier
 "BAR 

How I can deal with that?

Upvotes: 1

Views: 60

Answers (3)

Aleks-Daniel Jakimenko-A.
Aleks-Daniel Jakimenko-A.

Reputation: 10653

Just don't do that.

And read Bash FAQ #50

  1. I'm trying to save a command so I can run it later without having to repeat it each time

If you want to put a command in a container for later use, use a function. Variables hold data, functions hold code.

pingMe() {
    ping -q -c1 "$HOSTNAME"
}

[...]
if pingMe; then ..

Upvotes: 2

konsolebox
konsolebox

Reputation: 75458

The proper way to do that is to use an array instead:

CMD=(export FOO="BAR BAR")
"${CMD[@]}"

Upvotes: 0

Alfe
Alfe

Reputation: 59416

You should not use a variable as a command by just calling it (like in your $CMD). Instead, use eval to evaluate a command stored in a variable. Only by doing this, a true evaluation step with all the shell logic is performed:

eval "$CMD"

(And use double quotes to pass the command to eval.)

Upvotes: 3

Related Questions