o4-mini-2025-04-16· OpenAI
LMArena Human Preference 140K
bash中mapfile如何接收来自管道的数据
- User
bash中mapfile如何接收来自管道的数据
- Assistant
在 Bash 中,
mapfile(在早期版本里也叫readarray)默认就是从标准输入读取数据并按行填入数组。常见的“从管道拿数据”有两种思路:- 进程替换(Process Substitution)
# 举例:把 `ls` 的输出读进数组 arr mapfile -t arr < <(ls -1) # 验证 declare -p arr解释:
< <( … )是进程替换,把子进程的 stdout 当作一个临时文件传给mapfile。-t去掉每行末尾的换行符(常用)。
- 管道 + lastpipe
默认情况下,管道的每个命令都在子 shell 里跑,写在管道里的mapfile拿到的数组会丢失在父 shell 里。
如果你在脚本里并且不在交互模式(或者 Bash 4.2+、打开了lastpipe),可以:
#!/usr/bin/env bash shopt -s lastpipe # 只对非交互脚本生效 set -o pipefail # 这下 mapfile 就在主 shell 中执行了 echo -e "a\nb\nc" | mapfile -t arr declare -p arr⚠️ 注意:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.