bash - Bash,如何在一行代码中创建一个数组
问题描述
如何一步创建数组而不是两个阶段,如下所示?下面的示例是在实时 Linux 系统上执行的。
POSITION=`volt |grep ate |awk '{print $4}'` #returns three integers
declare -a POSITION_ARRAY=($POSITION) #create an array
解决方案
正如 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 分隔的整数,这将满足您的要求。但从任意命令输出中填充数组并不是一种安全的方法,因为不带引号的扩展将是分词和通配符。
将命令的输出读入按行分割的数组的正确方法是使用readarray
builtin,如下所示:
readarray -t POSITION_ARRAY < <(volt | grep ate | awk '{print $4}')
推荐阅读
- angular - 将由多个表单组组成的表单数组动态绑定到Angular 12的反应形式的模板时出错
- amazon-web-services - 如何跨多个 AWS Cloudwatch 日志流查找我的 Python lambda 函数的错误日志?
- python - 如何以管理员形式显示模型的外键字段
- javascript - Livewire Competent 重新渲染时更新 Alpinejs 绑定
- python - 如何计算测量的平均值和标准偏差,以使信噪比为特定值?
- javascript - 选择反应 POST
- 物品编号
- r - R中的可滚动绘图访问时间
- python - 将键值元组转换为逗号字符串
- python - 当使用定义的 USER_AGENTS 运行 scrapy spider 时,抓取的项目停止在 1000 个计数
- jquery - 用jquery改变特定标题的颜色