首页 > 解决方案 > Bash,如何在一行代码中创建一个数组

问题描述

如何一步创建数组而不是两个阶段,如下所示?下面的示例是在实时 Linux 系统上执行的。

POSITION=`volt |grep ate |awk '{print $4}'` #returns three integers 
declare -a POSITION_ARRAY=($POSITION)  #create an array  

标签: bash

解决方案


正如 wjandrea 所说,您不需要中间变量。这两个片段是等价的:

POSITION=$(volt | grep ate | awk '{print $4}')
declare -a POSITION_ARRAY=($POSITION)
# declare -a also works, but isn't needed in modern Bash
POSITION_ARRAY=( $(volt | grep ate | awk '{print $4}') )

如果您知道管道的输出是 witespace 分隔的整数,这将满足您的要求。但从任意命令输出中填充数组并不是一种安全的方法,因为不带引号的扩展将是分词和通配符

将命令的输出读入按行分割的数组的正确方法是使用readarraybuiltin,如下所示:

readarray -t POSITION_ARRAY < <(volt | grep ate | awk '{print $4}')

推荐阅读