Skip to content

Instantly share code, notes, and snippets.

@mhed89
Created February 3, 2023 18:55
Show Gist options
  • Select an option

  • Save mhed89/14bbe0f46f71c29b6b6da78cff267e8a to your computer and use it in GitHub Desktop.

Select an option

Save mhed89/14bbe0f46f71c29b6b6da78cff267e8a to your computer and use it in GitHub Desktop.
Get the first N lines of a file
head() {
# Usage: head "n" "file"
while IFS= read -r line; do
printf '%s\n' "$line"
i=$((i+1))
[ "$i" = "$1" ] && return
done < "$2"
# 'read' used in a loop will skip over
# the last line of a file if it does not contain
# a newline and instead contains EOF.
#
# The final line iteration is skipped as 'read'
# exits with '1' when it hits EOF. 'read' however,
# still populates the variable.
#
# This ensures that the final line is always printed
# if applicable.
[ -n "$line" ] && printf %s "$line"
}
# Usage
$ head 2 ~/.bashrc
# Prompt
PS1='➜ '
$ head 1 ~/.bashrc
# Prompt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment