user3152289 user3152289 - 1 month ago 12
Bash Question

Linux bash: How can I use the eval command correctly?

I can run the following command on the Linux command line and it correctly lists all the files that have the ABC- and XYZ- prefixes:

ls {ABC-,XYZ-}*.xml

Result: ABC-01.xml ABC-02.xml ABC-03.xml XYZ-01.xml XYZ-02.xml


Now, I figured that I could use a variable as follows:

file_pfx={ABC-,XYZ-}


and then use the variable in the "ls" command combined with "eval":

eval 'ls ${file_pfx}*.xml'

Result: ls: {ABC-,XYZ-}*.xml: No such file or directory


What am I doing wrong?

Thanks

Answer Source

You should use double quotes to allow variable expansion ($file_pfx):

eval "ls ${file_pfx}*.xml"

Notice I'm assuming your filenames don't contain spaces.

Anyway, be careful with the use of eval.