代码之家  ›  专栏  ›  技术社区  ›  user5507535

Bash中带有预处理值或附加值的Readarray

  •  1
  • user5507535  · 技术社区  · 4 年前

    在Bash中,如果我想获得所有可用键盘布局的列表,但要预先添加我自己的键盘布局,我可以这样做:

    readarray -t layouts < <(localectl list-x11-keymap-layouts)
    layouts=("custom1" "custom2" "${kb_layouts[@]}")
    

    如果我想追加,我可以这样做:

    readarray -t layouts < <(localectl list-x11-keymap-layouts)
    layouts=("${kb_layouts[@]}" "custom1" "custom2")
    

    是否有可能在单行中实现相同的目标 readarray 命令?

    1 回复  |  直到 4 年前
        1
  •  6
  •   Shawn    4 年前

    您可以使用 -O 选择 mapfile / readarray 指定起始索引。所以

    declare -a layouts=(custom1 custom2)
    readarray -t -O"${#layouts[@]}" layouts < <(localectl list-x11-keymap-layouts)
    

    将在数组中的现有值之后添加命令行,而不是覆盖现有内容。

    您可以使用以下命令一次将多个值附加到现有数组中 +=(...) :

    readarray -t layouts < <(localectl list-x11-keymap-layouts)
    layouts+=(custom1 custom2)
    
        2
  •  4
  •   Inian    4 年前

    由于过程替代输出 <(..) 被FIFO所取代,以便进程从中消费,您可以在其中添加更多选择的命令。例如,添加 "custom1" "custom2" 你只需要做

    readarray -t layouts < <(
      localectl list-x11-keymap-layouts; 
      printf '%s\n' "custom1" "custom2" )
    

    这将创建一个FIFO,其中包含来自两个FIFO的内容 localectl 输出和 printf 输出,以便 readarray 可以将它们视为另一个唯一的非空行。对于预添加操作,请与 输出函数 输出之后 本地 输出。