mapfile also called (read array) is a command of the Bash shell used to read arrays. It reads lines from the standard input into an array variable. Also, mapfile must read from substitution (< <) and not from a pipe.
Only available from bash 4.
Also, mapfile is faster and more convenient when compared to a read loop. It returns 1 or 0 depending on whether the command was successful or not. If no array name is not specified, the default variable MAPFILE is used as the target array variable.
Syntax: mapfile [array]
Alternatively, we can use read array [arrayname] instead of mapfile.
Example 1. Reading an array from a file:
$ mapfile MYFILE < example.txt
$ echo ${MYFILE[@]}
$ echo ${MYFILE[0]}
Example 2. Capture the output into an array:
$ mapfile TESTARRAY < <(printf "Item 1\nItem 2\nItem 3\n")
$ echo ${TESTARRAY[@]}
Here, Item1, Item2, and Item 3 have been stored in the array TESTARRAY.
Example 3. Strip newlines and store item using -t:
$ mapfile -t TESTARRAY< <(printf "Item 1\nItem 2\nItem 3\n")
$ printf "%s\n" "${TESTARRAY[@]}"
$ mapfile -n 2 TESTARRAY < example.txt
$ echo ${TESTARRAY[@]}
No comments:
Post a Comment