EN VI

Linux - Difference between empty string and empty file?

2024-03-17 22:30:04
How to Linux - 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?

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.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login