help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] (no subject)


From: John McKown
Subject: Re: [Help-bash] (no subject)
Date: Fri, 22 Sep 2017 09:54:37 -0500

On Fri, Sep 22, 2017 at 9:00 AM, Lakshman Siddardha <
address@hidden> wrote:

> file:list
> ----------------------------------------
> hello
> world
> ----------------------------------------
>
> when i type on terminal the following command:
> $ cat $file
>
> it displays as it is in file
> ----------------------------------------
> hello
> world
> ----------------------------------------
>
> when i execute a shell script, it gives output in one line only
> ---------------------------------------
> ex.sh
> ----------------------------------------
> lista=$(cat list)
> echo $lista
> -------------------------------------
>
> it gives output of
> --------------------------
> hello world
> -------------------------
>
> i want new line character between "hello" and "world"
>

​This is "working as designed". Why? Well when the "cat list" is executed,
the output, as you know, is: hello\nworld\n (where \n is the C escape
representing the <newline> character). Now, the key to this entire thing is
understanding how BASH interprets this character string. BASH, by default,
splits the the command line according to the characters in the IFS
environment variable, if set. If IFS is not set, then BASH splits the
command line at every <tab>, <space>, or <newline>. So the the <newline> is
treated the same as a <space>, and you end up with two parameters (hello)
and (world) which are concatenated back together with a separating <space>.
It's just how BASH works. Now, after all that, which I recognize is likely
not really a very good explanation, what you can do IN THIS CASE, is to
"temporarily" set the IFS environment variable to "nothing" just for the
assignment. That is, do:

IFS="" lista=$(cat list)
echo $lista

-- 
*L'Shanah Tovah Tikatevu*

Maranatha! <><
John McKown


reply via email to

[Prev in Thread] Current Thread [Next in Thread]