1

Many files in my Git repo are missing a trailing newline:

GitHub notice "No newline at end of file"

For consistency, and to remove git-related visual clutter, I would like to automatically add it where it is missing.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
P i
  • 29,020
  • 36
  • 159
  • 267

1 Answers1

7
#!/bin/bash

RED='\033[0;31m'
GREEN='\033[0;32m'
GREY='\033[0;30m'
RESET='\033[0m' # No Color

#files=$(find ./files -type f)
files=$(git ls-files)

for file in $files; do
    if [[ $(tail -c 1 "$file" | xxd -p) != 0a ]]; then
        echo -en "Fix ${RED}$file${RESET}? (y/n) "
        read -n 1  answer
        echo
        if [[ $answer = 'y' ]]; then
            echo -e "FIXING ${GREEN}$file${RESET}"
            echo >> $file
        else
            echo "Skipping $file"
        fi
    else
        echo -e "${GREY}$file has newline${RESET}"
    fi
done

P i
  • 29,020
  • 36
  • 159
  • 267
  • 2
    You get the nod for a nicely written script, but I would be hesitant to include ANSI escapes for color. While supported by VT terminals, there is no guarantee the OP uses a compatible terminal and they are superfluous to the script operation. Not a knock, just a consideration. – David C. Rankin Dec 15 '20 at 05:39