【问题标题】:For each line in command output add to array [duplicate]对于命令输出中的每一行,添加到数组 [重复]
【发布时间】:2017-04-18 11:07:51
【问题描述】:

我正在尝试在 bash 脚本中执行以下操作:将所有不以 /dev/sda 开头的设备节点文件添加到名为 devices 的数组中。由于脚本将在只读文件系统上执行,我不能使用此处的文档。

这是我的代码:

devices=()
ls -1 /dev/hd* /dev/sd* | while read -r device; do
    if [[ "$device" != "/dev/sda"* ]]; then
        devices+=($device)
    fi
done

我不明白为什么在命令末尾,devices 仍然是空的。例如,我可以通过在将其添加到数组之前/之后添加命令echo $device 来成功打印每个项目。但是为什么不添加它们呢?

此外,如果我使用此处的文档运行相同的命令,一切正常:

devices=()
while read -r device; do
    if [[ "$device" != "/dev/sda"* ]]; then
        devices+=($device)
    fi
done <<< $(ls -1 /dev/hd* /dev/sd*)

在这些命令的末尾,数组devices 被正确填充。

您能帮我理解为什么第一个代码提取不起作用而第二个代码提取起作用吗?我做错了什么?

【问题讨论】:

    标签: arrays bash pipe heredoc


    【解决方案1】:

    好的。我通过使用 bash Process Substitution 解决了我的问题:

    devices=()
    while read -r device; do
        if [[ "$device" != "/dev/sda"* ]]; then
            devices+=($device)
        fi
    done < <(ls -1 /dev/hd* /dev/sd*)
    

    这样就可以了。

    【讨论】:

      【解决方案2】:

      您不需要使用lsread 或进程替换。只需使用 for 循环即可。

      devices=( /dev/hd* )
      for device in /dev/sd*; do
          [[ $device != /dev/sda* ]] && devices+=("$device")
      done
      

      事实上,使用扩展模式,您甚至不需要循环。

      shopt -s extglob
      devices=( /dev/hd* /dev/sd!(a)* )
      

      【讨论】:

        猜你喜欢
        • 2020-02-04
        • 2019-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-31
        • 1970-01-01
        • 2018-11-04
        相关资源
        最近更新 更多