brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: mapfile -t loads command output into a shell array, one line per item

Shell
~/tips/tip-shell-mapfile-t-array

mapfile -t logs < <(find /var/log -name '*.log')

Reads the lines of a command into a bash array without word splitting problems.

Splitting output by lines with a for loop breaks on spaces, and mapfile does not.

mapfile -t logs < <(find /var/log -name '*.log')
echo "${#logs[@]} files"
printf '%s\n' "${logs[0]}"

-t removes the trailing newline from every item, so you get clean paths. ${#logs[@]} is the number of items and "${logs[@]}" expands every item as a separate word. mapfile needs bash 4 or newer, so the stock bash 3.2 on macOS does not have it. In zsh you can use ${(f)"$(cmd)"} instead.

Further reading: Bash manual: mapfile

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link