user3401516
user3401516

Reputation: 103

Bash add newline if missing

I have difficulties in understanding the following code:

    lastline=$(tail -n 1 $bc; echo x); lastline=${lastline%x}
    if [ "${lastline: -1}" != $'\n' ]; then
        echo >> $bc
    fi

I suppose it's all about adding a \n in the file $bc if the last line is not already one. However echo x and lastline%x and ${lastline: -1} does not make sense to me at all. What am I missing?

The file $bc contains only lines like:

Sample1,ATAGFAT

Upvotes: 2

Views: 1634

Answers (1)

anubhava
anubhava

Reputation: 785276

This is basically a check if your file $bc is not ending with newline then add a newline in it.

  • tail -n 1 $bc; echo x - Prints last line of file $bc and then prints literal x
  • ${lastline%x) - removes x from your file data $lastline
  • "${lastline: -1}" - reads last character from variable $lastline
  • "${lastline: -1}" != $'\n' - compares last character with newline character
  • echo >> $bc adds a newline if above check fails

Upvotes: 4

Related Questions