Created
February 3, 2023 18:55
-
-
Save mhed89/14bbe0f46f71c29b6b6da78cff267e8a to your computer and use it in GitHub Desktop.
Get the first N lines of a file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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