How Can I Store a Wildcard in a Variable

I have the following code:

target="file.txt"
ls "$target"

Output:

file.txt

This does not work with a wildcard:

target="*"
ls "$target"

Output:

ls: cannot access '*': No such file or directory

The issue is that it is being wrapped in quotes. It is doing ls '*' instead of ls *.

Answers 1

  • When you quote the $target, you're telling the shell not to expand the wildcard. Try leaving the quotes off:

    target="*"
    ls $target
    

    and you'll get a directory listing.

    What other values might target have though? Might it have spaces? Question marks? How would you want them to be treated?


Related Questions