5

Here's the code I need:

#!/bin/sh

x1="a1 a2"
x2="b1 b2"

list=SOMETHING

for x in "$list"
do
    echo $x
done

And the output I want:

a1 a2
b1 b2

The question is: what should SOMETHING be? I want $list to behave just as $@ does.

Notes: I can't use $IFS and I can't eval the entire loop.

dandu
  • 800
  • 1
  • 8
  • 18
  • 1
    related: https://unix.stackexchange.com/questions/102891/posix-compliant-way-to-work-with-a-list-of-filenames-possibly-with-whitespace/102904 | bash: https://stackoverflow.com/questions/9084257/bash-array-with-spaces-in-elements – Ciro Santilli OurBigBook.com Apr 21 '18 at 08:27

2 Answers2

3

This is probably as close as you can get:

#!/bin/sh
x1="a1 a2"
x2="b1 b2"

set -- "$x1" "$x2"

for x in "$@"
do
    # echo $x
    echo "[${x}]"    # proves that the lines are being printed separately
done

Output:

[a1 a2]
[b1 b2]

In Bash you can use an array:

#!/bin/bash
x1="a1 a2"
x2="b1 b2"

list=("$x1" "$x2")

for x in "${list[@]}"
do
    # echo $x
    echo "[${x}]"    # proves that the lines are being printed separately
done

Same output.

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
0

It is not possible in standard POSIX shell.

stepancheg
  • 4,262
  • 2
  • 33
  • 38