Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash interprets && as an argument

Tags:

linux

bash

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”.

like image 268
Jason Javier Avatar asked Jul 29 '26 22:07

Jason Javier


1 Answers

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.

like image 120
John Kugelman Avatar answered Aug 01 '26 06:08

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!