当前位置: 动力学知识库 > 问答 > 编程问答 >

bash - POSIX SH build loop variable with elements containing spaces

问题描述:

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 [email protected] does.

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

网友答案:

This is probably as close as you can get:

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

set -- "$x1" "$x2"

for x in "[email protected]"
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.

网友答案:

It is not possible in standard POSIX shell.

分享给朋友:
您可能感兴趣的文章:
随机阅读: