Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between empty string and empty file

I find it confusing that I can read once from an empty string, but not from an empty file:

while read -r foo; do echo ${#foo}; done <<< ''      # prints '0'
while read -r foo; do echo ${#foo}; done < /dev/null # prints nothing

Is there a way to write a string literal that cannot be read from even once? Conversely, what contents does a file need to have, in order to be able to read exactly one empty string from it, and nothing else?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Refer to the bash manual description of here strings:

3.6.7 Here Strings

A variant of here documents, the format is:

[n]<<< word

The word undergoes tilde expansion, parameter and variable expansion,
command substitution, arithmetic expansion, and quote removal.
Filename expansion and word splitting are not performed. The result is
supplied as a single string, with a newline appended, to the command
on its standard input (or file descriptor n if n is specified).

Note "with a newline appended". Even if your string starts out empty, it ends up containing at least a newline when used in this fashion. A string or file containing just a newline will be interpreted as one blank line by the while read loop.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading