【问题标题】:Readarray with preppended or appended values in Bash在 Bash 中带有前置或附加值的读取数组
【发布时间】:2020-11-11 08:26:58
【问题描述】:

在 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 命令中的一行中实现相同的功能?

【问题讨论】:

  • 您要追加到已由localectl 命令填充的数组layouts?
  • @Inian 是的,但同时进行,我的意思是使用相同的 readarray 命令添加自定义值。我尝试了不同的方法,但没有奏效。不知道有没有可能。
  • 追加到数组,可以使用+= --> layouts+=(custom1 custom2)

标签: arrays linux bash append prepend


【解决方案1】:

您可以使用-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】:

    由于进程替换输出 &lt;(..) 被替换为 FIFO 以供进程使用,因此您可以在其中添加更多选择命令。例如。追加"custom1" "custom2" 你只需要这样做

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

    这将创建一个包含来自localectl 输出和printf 输出的内容的FIFO,以便readarray 可以将它们作为另一个唯一的非空行来读取。对于前置操作,与printf 输出相同,然后是localectl 输出。

    【讨论】:

    • 哦,我试过了,但我想我忘记了;,这就是它不起作用的原因。谢谢!
    猜你喜欢
    • 2015-08-06
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    • 2020-01-16
    • 1970-01-01
    • 2011-09-18
    相关资源
    最近更新 更多