[ALUG] Bash Substitution

James Bensley jwbensley at gmail.com
Fri Dec 10 18:18:52 GMT 2010


On 7 December 2010 21:03, Richard Parsons <richard.lee.parsons at gmail.com> wrote:
>
> If I do:
>
> echo "1
> 2
> 3" > test
>
> and then cat test, then I can see the contents of the file, including the new lines.

This is because you have literally written "1{ENTER}2{ENTER}3" in the
terminal. Echo'ing this out to the file "test" will save the ASCII
string you have written (new line characters are ASCII characters). If
you use hexdump you can see this (I'm on my Mac but I believe its a
fairly standard command);

james$ hexdump ./test
0000000 31 0a 32 0a 33 0a
0000006

Here we see the decimal for 1,2 and 3 in hex, 31, 32 and 33
respectively. Each is separated by '0a' which is the decimal value 10
written in hex. 10 is the ASCII character for a new line feed, NL). So
cat'ing the file we have '1{NL}2{NL}3'. So far so good.

> However, if I do:
>
> VARIABLE=$(cat test)
> echo $VARIABLE
>
> then the output has spaces instead of new lines.  Why is that?

Surround your variable in quote marks " to echo new lines;

james$ ./myscript
1
2
3
james$ cat ./myscript
mine=$(cat test)
echo "$mine"

>And how could I stop that from happening?

What do you mean, how can you stop displaying spaces and display new
lines instead? As above, use quote marks. Or do you mean something
else?

HTH.

-- 
Regards,
James.

http://www.jamesbensley.co.cc/

There are 10 kinds of people in the world; Those who understand
Vigesimal, and J others...?



More information about the main mailing list