← 返回命令列表

Linux command

mapfile 命令

文件

复制后可按需替换文件名、目录或参数。

常用示例

Read file into array

mapfile [array] < [file.txt]

Read with line limit

mapfile -n [10] [array] < [file.txt]

Skip first N lines

mapfile -s [2] [array] < [file.txt]

Remove trailing newlines

mapfile -t [array] < [file.txt]

Use specific delimiter

mapfile -d ':' [array] < [file.txt]

Read from command

mapfile [array] < <(ls)

说明

mapfile (also known as readarray) is a bash builtin that reads lines from standard input into an indexed array variable. Without a variable name, it uses the default array `MAPFILE`. It is significantly faster than a `while read` loop for reading files into arrays, as it is implemented as a builtin rather than running in a subshell.

参数

-n _COUNT_
Maximum lines to read.
-s _COUNT_
Lines to skip.
-t
Remove trailing delimiters.
-d _DELIM_
Use delimiter instead of newline (bash 4.4+).
-O _ORIGIN_
Start assigning at array index ORIGIN (default: 0).
-u _FD_
Read from file descriptor FD instead of standard input.
-C _CALLBACK_
Evaluate CALLBACK after reading each quantum of lines.
-c _QUANTUM_
Number of lines between CALLBACK calls (default: 5000).

FAQ

What is the mapfile command used for?

mapfile (also known as readarray) is a bash builtin that reads lines from standard input into an indexed array variable. Without a variable name, it uses the default array `MAPFILE`. It is significantly faster than a `while read` loop for reading files into arrays, as it is implemented as a builtin rather than running in a subshell.

How do I run a basic mapfile example?

Run `mapfile [array] < [file.txt]` in a terminal, then adjust file names, paths, flags, or remote targets for your system.

What does -n _COUNT_ do in mapfile?

Maximum lines to read.