From 74957258f5eebf93af4c4e4712600bec35852422 Mon Sep 17 00:00:00 2001 From: E5ten Date: Tue, 1 Oct 2019 22:51:46 -0400 Subject: [PATCH] Fix negative args and files without ending \n If arg is negative, make the max lines it subtracted from the file length, like other head implementations Don't remove trailing newlines with mapfile, and don't add them with printf, to avoid printing an extra newline when a file doesn't end with one. --- bin/head | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/bin/head b/bin/head index d6f14f7..ad6d9f5 100755 --- a/bin/head +++ b/bin/head @@ -2,6 +2,8 @@ # # head in pure bash. +max_lines=10 + while getopts ":n:" opt; do case $opt in n) max_lines="$OPTARG" ;; @@ -25,5 +27,6 @@ done exit 1 } -mapfile -tn "${max_lines:-10}" file_data < "$1" -printf '%s\n' "${file_data[@]}" +mapfile file_data < "$1" +[[ ${max_lines##-*} || $((max_lines += ${#file_data[@]})) ]] +printf '%s' "${file_data[@]0:max_lines}"