Bash: prevent read to remove spaces
Hello, linuxquestions.
I have reading "Unix and Linux adminitration handbook", and faced with a problem: I have command: Code:
alex@just ~ $ echo one two; echo three four | while read -e "fname"; do echo ${fname} ; done |
Here's a hint:
Code:
[mherring@herring_lap play]$ echo $var |
You can print multiple space(s) using \n or tab(s) using \t, as:
Code:
echo -e "three\nfour" # For one space Code:
three four |
Quote:
|
Quote:
Code:
alex@just ~ $ echo "one two"; echo "three four" | while read fname; do echo "$fname" ; done |
It's vital in scripting to understand how the shell handles arguments and whitespace. Study these links for the details:
http://mywiki.wooledge.org/Arguments http://mywiki.wooledge.org/WordSplitting http://mywiki.wooledge.org/Quotes The function of the echo command is to print each and every argument it gets separately, with a single space between them. Since your text strings are unquoted the shell breaks the them up into their individual words before echo processes them. Next, if we look closely at your original scriptlet: Code:
$ echo one two; echo three four | while read -e "fname"; do echo ${fname} ; done Next, you should be aware of the variable scoping limitation when using pipes. The above will work as long as you are only echoing the results, but it wouldn't work if you needed to set variables that are still needed after the loop terminates. The recommended bash syntax is to instead feed the loop with a process substitution or a here doc/here string. Code:
while read -r fname; do The -e option to read is also superfluous if you aren't using it interactively, BTW. But it is recommended to always use the -r option, particularly if the input text can contain literal backslashes. Finally, be aware that printf is often a better choice when you simply need to output your data on multiple lines, since it has implicit looping built into it. Code:
printf '%s\n' 'one two' 'three four' |
David the H., thanks for such a detailed response!
I will study links,that you have posted. |
Glad to help out.
I should probably also have included BashFAQ #1, which is all about how to properly read lines of text input. When you get a chance, also take the time to read through the whole BashGuide from the same site. It provides an excellent overview of all the basics you should know for good scripting. Then round it off with the BashPitfalls, to help you avoid common errors. |
All times are GMT -5. The time now is 04:01 AM. |