Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior I don't understand in bash

Tags:

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*

Up to here, I think I understand. But:

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

I was expecting ab*. This means that there is a basic that I don't understand.

I've been searching for single vs double quotes, expansion and more in bash tutorials and manuals but I don't get it yet.

like image 982
Diego Herranz Avatar asked Dec 24 '13 19:12

Diego Herranz


People also ask

Is bash difficult to learn?

Overall, Bash is relatively easy to learn. Most students can learn basic, intermediate, and advanced commands within six months.

What $@ means in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What does $_ mean in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.

Do people still use bash?

The biggest advantage to learning Bash is that it's so widely used. Even if you're working in another programming language like Python or Ruby, it's worth learning Bash because many languages support Bash commands to pass data and information to and from your computer's OS.


2 Answers

The line $ echo $myvariable is being parsed by first substituting the contents of $myvariable into the line, then running the line. So when the line is parsed by bash, it looks like $ echo ab*.

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

like image 130
Andrey Mishchenko Avatar answered Oct 22 '22 16:10

Andrey Mishchenko


BASH isn't performing the expansion during the assignment, its expanding when you run the echo command. So with both kinds of quotes, you are storing the raw string ab* to your variable. To see this behaviour in action, use quotes when you echo as well:

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$
like image 2
jprice Avatar answered Oct 22 '22 16:10

jprice