Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

echo inside a for loop lists files matching the output pattern

I have a problem with the following for loop:

X="*back* OLD"
for P in $X
do
echo "-$P"
done

I need it to output just:

-*back*
-OLD

However, it lists all files in the current directory matching the *back* pattern. For example it gives the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

-backup.bkp
-backup_new.bkp
-backup_X
-OLD

How to force it to output the exact pattern?

>Solution :

Use an array, as unquoted parameter expansions are still subject to globbing.

 X=( "*back*" OLD )
 for P in "${X[@]}"; do
     printf '%s\n' "$P"
 done

(Use printf, as echo could try to interpret an argument as an option, for example, if you had n in the value of X.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading