Prevent glob expansion in foo="*"; echo $foo

5,343

Let us define foo:

$ foo="*"

Now, try echo without quotes:

$ echo $foo
File1 File2

The replacement of * with a list of filenames is called pathname expansion. It can be suppressed with with double-quotes:

$ echo "$foo"
*

In addition, double-quotes will prevent brace expansion, tilde expansion, and word splitting.

For completeness, try echo with single quotes:

$ echo '$foo'
$foo

Single quotes prevent the shell from making any substitutions at all.

Share:
5,343

Related videos on Youtube

Amelio Vazquez-Reina
Author by

Amelio Vazquez-Reina

I'm passionate about people, technology and research. Some of my favorite quotes: "Far better an approximate answer to the right question than an exact answer to the wrong question" -- J. Tukey, 1962. "Your title makes you a manager, your people make you a leader" -- Donna Dubinsky, quoted in "Trillion Dollar Coach", 2019.

Updated on September 18, 2022

Comments

  • Amelio Vazquez-Reina
    Amelio Vazquez-Reina almost 2 years

    In Bash, when I do:

    foo="*"
    echo $foo
    

    It expands * to the contents of the current folder. How do I make sure it just prints a literal *?

    The same, by the way, happens with a regular echo "$foo", it prints the contents of the current folder.

    • Admin
      Admin about 9 years
      Thanks @don_crissti: It works, but it prints the contents of the current folder.
    • Admin
      Admin about 9 years
      @don_crissti My wrong! Sorry I read that too quickly. Can't believe I fell victim to this.
  • Amelio Vazquez-Reina
    Amelio Vazquez-Reina about 9 years
    Of course! I can't believe I missed this. I kept thinking of quoting the original assignment, not the expansion on the echo statement itself!