Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When setting IFS to split on newlines, why is it necessary to include a backspace?

Tags:

linux

bash

I'm curious as to why the backspace is necessary when setting IFS to split on newlines like this:

IFS=$(echo -en "\n\b") 

Why can I not just use this (which doesn't work) instead?

IFS=$(echo -en "\n") 

I'm on a Linux system that is saving files with Unix line endings. I've converted my file with newlines to hex and it definitely only uses "0a" as the newline character.

I've googled a lot and although many pages document the newline followed by backspace solution, none that I have found explain why the backspace is required.

-David.

like image 265
user431931 Avatar asked May 30 '13 08:05

user431931


People also ask

How do you create a new line in IFS?

Use the backslash n escape sequence to set the IFS to a newline only. Now, spaces and tabs will be ignored. Only a newline will be treated as the delimiter.

What is default IFS in bash?

The default value of IFS is a three-character string comprising a space, tab, and newline: $ echo "$IFS" | cat -et ^I$ $ Here we used the -e and -t options of the cat command to display the special character values of the IFS variable.


2 Answers

Because as bash manual says regarding command substitution:

Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted.

So, by adding \b you prevent removal of \n.

A cleaner way to do this could be to use $'' quoting, like this:

IFS=$'\n' 
like image 190
spbnick Avatar answered Oct 22 '22 02:10

spbnick


I just remembered the easiest way. Tested with bash on debian wheezy.

IFS=" " 

no kidding :)

like image 22
moddie Avatar answered Oct 22 '22 00:10

moddie