Jason Javier Jason Javier - 1 month ago 9
Linux Question

Bash interprets && as an argument

Observe the following

[admin@myVM ~]$ test="echo hello && echo world"
[admin@myVM ~]$ $test
hello && echo world
[admin@myVM ~]$ echo hello && echo world
hello
world


It seems that if you place && into a bash variable and execute it as a command, bash interprets && as a string argument. Does anyone know how to alter this behavior? That is to say, does anyone know how to tell bash “I want to execute double ampersand”.

Answer

Variables are not meant to store scripting. Store code in functions, not variables.

$ test() { echo hello && echo world; }
$ test
hello
world

The reason $test doesn't work is because unquoted variable expansions are only subjected to two of bash's many phases of parsing:

  1. Word splitting
  2. Globbing

That means it will split apart $test into separate words, which is why it recognizes the echo command. It will also expand wildcards AKA globs. Those are the only two bits of parsing it does, though. It doesn't look for symbols like &&, |, or ;.

I don't recommend it, but you can get bash to execute your string with bash -c "$test" or eval "$test". These are bad habits that you should avoid unless absolutely necessary. Functions are much better than hacks with eval, and they don't open up potential security holes by allowing arbitrary code execution.