0
list="name1 name2 name3 name4"
dir="/test/dir"
for i in $dir/${list};do echo $i;done;

I get

/test/dir/name1
name2
name3
name4

I want

/test/dir/name1
/test/dir/name2
/test/dir/name3
/test/dir/name4

Note: I currently have a working solution for i in ${list};do echo $dir/$i;done; but would like to know why the above command isn't yielding the desired outcome and if there's any tweak to make it work. Thanks

1
  • Your current working solution will break if there are white space involve/included in the value of the assignment, because variables is not quoted.
    – Jetchisel
    Apr 13, 2020 at 21:54

1 Answer 1

1

but would like to know why the above command isn't yielding the desired outcome

The "$list" expand as one argument/element

list='name1 name2 name3 name4'; printf '<%s>\n' "$list"

Output

<name1 name2 name3 name4>

If you use an array it expands each element separate by IFS

list=(name1 name2 name3 name4); printf '<%s>\n' "${list[@]}"

Output

<name1>
<name2>
<name3>
<name4>

Using an array for the list.

list=(name{1..4})  ##: this expands to name1 name2 name4 because of brace expansion.
dir="/test/dir"

##: prefend "$dir/" in every element in the array list using /#/
for i in "${list[@]/#/"$dir/"}"; do 
  echo "$i"
done

Output

/test/dir/name1
/test/dir/name2
/test/dir/name3
/test/dir/name4

Or if the goal is just to add the path, you can just print directly.

printf '%s\n' "${list[@]/#/"$dir/"}"
3
  • what if I have something likelist="name1 fileA testB name4" as supposed to having list="name1 name2 name3 name4" Apr 14, 2020 at 4:05
  • Right, then don't use brace expansion, list=(name1 fileA testB name4)
    – Jetchisel
    Apr 14, 2020 at 4:08
  • Although the name can be done with name{1,4} and the file to file{A,B}
    – Jetchisel
    Apr 14, 2020 at 4:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .