Linux bash:多变量赋值 [英] Linux bash: Multiple variable assignment
问题描述
Linux bash 中确实存在类似于 PHP 中的以下代码的内容:
Does exist in linux bash something similar to the following code in PHP:
list($var1, $var2, $var3) = function_that_returns_a_three_element_array() ;
即你在一个句子中为 3 个不同的变量分配了一个对应的值.
i.e. you assign in one sentence a corresponding value to 3 different variables.
假设我有一个 bash 函数 myBashFuntion
将字符串qwert asdfg zxcvb"写入标准输出.是否可以执行以下操作:
Let's say I have the bash function myBashFuntion
that writes to stdout the string "qwert asdfg zxcvb".
Is it possible to do something like:
(var1 var2 var3) = ( `myBashFuntion param1 param2` )
等号左边的部分当然不是有效的语法.我只是想解释一下我的要求.
The part at the left of the equal sign is not valid syntax of course. I'm just trying to explain what I'm asking for.
不过,以下是有效的:
array = ( `myBashFuntion param1 param2` )
echo ${array[0]} ${array[1]} ${array[2]}
但是索引数组不像普通变量名那样具有描述性.
但是,我可以这样做:
But an indexed array is not as descriptive as plain variable names.
However, I could just do:
var1 = ${array[0]} ; var2 = ${array[1]} ; var3 = ${array[2]}
但这是我更希望避免的另外 3 个陈述.
But those are 3 more statements that I'd prefer to avoid.
我只是在寻找一种快捷语法.可能吗?
I'm just looking for a shortcut syntax. Is it possible?
推荐答案
我想到的第一件事:
read -r a b c <<<$(echo 1 2 3) ; echo "$a|$b|$c"
输出是,不出所料
1|2|3
这篇关于Linux bash:多变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!