Read file lines into array safely

mapfile -t strips newlines; handles spaces unlike for-loop word splitting

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}"

    basename, strip extension, and global replace without spawning sed/basename

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

    Native regex match extracts groups; note: don't quote the right-hand regex

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

    Run N parallel jobs safely with NUL separators for names with spaces

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

    Inspect exit code of every pipe stage; $? only reports the last command

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

    POSIX option parsing with arguments; -n takes a value, -v is a switch

all 12 bash commands