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

Asked By: Amarakon

||

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?

Answered By: dbrand666
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.