Read file lines into an array

mapfile -t strips newlines and keeps spaces, unlike word splitting in a for loop

mapfile -t lines < file.txt; printf '%s\n' "${lines[@]}"

tool
bash12 commands
tags
bashtroubleshooting

More bash commands

  • f=/var/log/app.log.gz; echo "${f##*/}" "${f%.*}" "${f//log/LOG}"

    Get the basename, strip the extension and replace text without calling sed or basename

  • [[ $s =~ ^([0-9]+)\.([0-9]+) ]] && echo "${BASH_REMATCH[1]}/${BASH_REMATCH[2]}"

    Built-in regex match that extracts groups. Note: do not quote the regex on the right side

  • find . -name '*.log' -print0 | xargs -0 -P"$(nproc)" -n1 gzip

    Run one job per CPU core. NUL separators keep file names with spaces safe

  • curl -s "$url" | jq .data; echo "${PIPESTATUS[@]}"

    Show the exit code of every command in a pipe. $? only gives the last one

  • while getopts "n:v" o; do case $o in n) ns=$OPTARG;; v) verbose=1;; esac; done

    POSIX option parsing: -n takes a value, -v is a simple switch

all 12 bash commands