POSIX SH构建循环变量,其元素包含空格 [英] POSIX SH build loop variable with elements containing spaces

查看:64
本文介绍了POSIX SH构建循环变量,其元素包含空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我需要的代码:

#!/bin/sh

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

list=SOMETHING

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

我想要的输出:

a1 a2
b1 b2

问题是:SOMETHING应该是什么?我希望$list的行为与$@相同.

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

注意:我不能使用$IFS,也不能eval整个循环.

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 "$@"
do
    # echo $x
    echo "[${x}]"    # proves that the lines are being printed separately
done

输出:

[a1 a2]
[b1 b2]

在Bash中,您可以使用数组:

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

相同的输出.

这篇关于POSIX SH构建循环变量,其元素包含空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆