POSIX SH string variable with elements containing spaces

Here is the code I need:

#!/bin/sh

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

list=SOMETHING

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

And the conclusion I want is:

a1 a2
b1 b2

Question: what should be SOMETHING? I want to $listbehave the same way $@.

Notes: I can not use $IFS, and I can not evalcycle.

+3
source share
2 answers

This is probably as close as possible:

#!/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

Conclusion:

[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

The same way out.

+1
source

In the standard POSIX shell, this is not possible.

0
source

Source: https://habr.com/ru/post/1747704/


All Articles