Contents
How to use IFS as a delimiter in read?
If you set IFS to | (i.e. IFS=| ), | will be treated as delimiters between words/fields when splitting a line of input. [donotprint] [/donotprint]In the read command, IFS is used to split the line of input so that each variable gets a single field of the input. The default value is . You can print it with the following command:
How to read everything at once in Bash?
You can read everything at once without using a while loop: read -r -d ” -a addr <<< “$in” # The -d ” is key here, it tells read not to stop at the first newline (which is the default -d) but to continue until EOF or a NULL byte (which only occur in binary data).– lhunathMay 28 ’09 at 6:14 66
How to split a string by newline characters?
…and then, since you are changing the separator, you don’t need to convert the to space anymore, so you can simplify it to: This approach will function unless $x contains a matching globbing pattern (such as ” * “) – in which case it will be replaced by the matched file name (s).
How to print a non-zero exit status in Bash?
In your case, with NUL-delimited records (with -d ” ), IFS= read -d ” -rn1 var would work the same as bash cannot store a NUL character in its variables anyway, so printf ‘\\0’ | read -rN1 var would leave $var empty and return a non-zero exit status.
How is the IFS variable used in read?
The IFS variable is used in as the input field separator. If you set IFS to | (i.e. IFS=| ), | will be treated as delimiters between words/fields when splitting a line of input. [donotprint]donotprint]In the read command, IFS is used to split the line of input so that each variable gets a single field of the input. .
Why do we set the IFS variable to an empty value?
So, in order to read each line literally, we need to make sure that no word splitting is going on. We do this by setting the IFS variable to an empty value. Note how we set IFS specifically for the duration of the read built-in. The IFS= read -r line sets the environment variable IFS (to an empty value) specifically for the execution of read .
How to observe what happens in a while loop?
To illustrate, we use two echo commands that supply two lines to the while loop. Observe what happens with -r: Now, observe what happens without -r: Without -r, two changes happened. First, the double-backslash was converted to a single backslash.