在 Bash 中读取带有前置或附加值的数组

use*_*535 4 linux arrays bash append prepend

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

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

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

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

是否可以在命令中用一行来实现相同的目的readarray

Sha*_*awn 7

您可以使用/-O选项来指定起始索引。所以mapfilereadarray

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

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

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

readarray -t layouts < <(localectl list-x11-keymap-layouts)
layouts+=(custom1 custom2)
Run Code Online (Sandbox Code Playgroud)