All newlines are removed when saving cat output into a variable

14,840

The shell is splitting the msgs variable so echo get multiple parameters. You need to quote your variable to prevent this to happen:

echo "$msgs"
Share:
14,840

Related videos on Youtube

MOHAMED
Author by

MOHAMED

Contact me on LinkedIn.

Updated on July 08, 2022

Comments

  • MOHAMED
    MOHAMED almost 2 years

    I have the following file

    linux$ cat test.txt
    toto
    titi
    tete
    tata
    

    Saving the cat output into a variable will discard the newlines

    linux$ msgs=`cat test.txt`
    linux$ echo $msgs
    toto titi tete tata
    

    How to keep the output containing the newlines in the variables?

  • jlliagre
    jlliagre almost 11 years
    Doesn't answer the question nor make sense. cat ignores its standard input when passed file name(s) as argument.
  • Jerry Green
    Jerry Green over 3 years
    Confusing yet simple. Bash in a nut-shell