Home > Enterprise >  echo inside a for loop lists files matching the output pattern
echo inside a for loop lists files matching the output pattern

Time:02-22

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:

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

How to force it to output the exact pattern?

CodePudding user response:

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

CodePudding user response:

Use set -o noglob before your loop and set o noglob after to disable and enable globbing.

CodePudding user response:

To prevent filename expansion you could read in the string as a Here String.

To iterate over the items, you could turn them into lines using parameter expansion and read them linewise using read. In order to be able to put a - sign as the first character, use printf instead of echo.

X="*back* OLD"
while read -r x
do printf -- '-%s\n' "$x"
done <<< "${X/ /$'\n'}"

Another way could be to use tr to transform the string into lines, then use paste with the - sign as delimiter and "nothing" from /dev/null as first column.

X="*back* OLD"
tr ' ' '\n' <<< "$X" | paste -d- /dev/null -

Both should output:

-*back*
-OLD
  • Related