Behavior I do not understand in bash

I have a folder with 3 dummy files: ab0, ab1 and ab2.

$ echo ab* ab0 ab1 ab2 $ myvariable=ab* $ echo $myvariable ab0 ab1 ab2 $ echo 'ab*' ab* 

So far, I think I understand. But:

 $ myvariable='ab*' $ echo $myvariable ab0 ab1 ab2 

I was expecting ab* . This means that there is a core that I do not understand.

I searched for single and double quotes, an extension, and more in bash tutorials and manuals, but I still don't understand.

+8
bash
source share
2 answers

The string $ echo $myvariable parsed, first substituting the contents of $myvariable into a string, and then running the string. Therefore, when a string is parsed using bash, it looks like $ echo ab* .

If you $ echo "$myvariable" , you will get the desired behavior.

+7
source share

BASH does not expand at the time of assignment; it expands when the echo command is run. Thus, with both types of quotes, you save the original string ab* in your variable. To see this behavior in action, use quotation marks when you echo :

 hephaestus:foo james$ echo ab* ab0 ab1 ab2 hephaestus:foo james$ var=ab* hephaestus:foo james$ echo $var ab0 ab1 ab2 hephaestus:foo james$ echo "$var" ab* hephaestus:foo james$ var='ab*' hephaestus:foo james$ echo $var ab0 ab1 ab2 hephaestus:foo james$ echo "$var" ab* hephaestus:foo james$ 
+2
source share

All Articles