如何在带有条的命令行中为多个变量分配值


10

我本质上是在尝试将shell命令的输出的某些部分分配给多个变量,但是我不知道该怎么做。

为了简单起见,假设执行时在shell上的命令可以打印

one two three four

可以用

echo "one two three four"

(尽管实际的建议不同)

现在,我想将输出的第二个和第四个单词(在本例中为两个四个)分配给变量w1w2

我以为我可以像这样使用read命令:

echo "one two three four" | awk '{print $2 " " $4}' | read w1 w2

但这不起作用,可能是因为read命令是在子进程中执行的。

那么,我将如何实现自己的追求?


Answers:


17

这不起作用,因为read在子进程中运行不会影响父级环境。

您有几种选择:

您可以将命令转换为:

w1=$(echo "one two three four" | awk '{print $2}')
w2=$(echo "one two three four" | awk '{print $4}')

或者,更改IFS并使用set

OIFS="$IFS"
IFS=' '
set -- $(echo "one two three four" | awk '{print $2" "$4}')
IFS="$OIFS"
w1=$1 w2=$2

或Here字符串:

read w1 w2 w3 w4 <<< "one two three four"

4
根据此处字符串:读取a1 a2 a3 <<< $(回显一二三)
Petr Uzel

非常感谢。我不知道的<<< Here String
勒内Nyffenegger

1
为了安全,你应该使用:read -rdo not allow backslashes to escape any characters
汤姆·黑尔
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.