Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a variable $myvar that contains two lines, and I want to put first of them into a new variable.

When I try:

$ myvar1 = $(echo $myvar | head -n 1) 

It doesn't work because echo doesn't output newlines as I am expecting.

Obviously I can do this:

$ myvar1 = $(echo $myvar | cut -d " " -f 1)

It will work as echo's output contains one word on the first line and one word on the second.

I have two questions:

  1. Why does echo print spaces instead of line breaks?
  2. Is it possible to make it easily or more correct (I'm not a professional in shell scripting, maybe I'm missing something here)
share|improve this question

1 Answer 1

up vote 5 down vote accepted

Wrap the argument to echo in quotation marks to retain whitespace properly.

echo "$myvar"

Otherwise the whitespace-separated elements of the value will be treated as individual arguments to echo.

$ ls -1
Desktop
Documents
Downloads
Movies
Music
Pictures
Sites

$ myvar="$( ls -1 )"

$ echo $myvar
Desktop Documents Downloads Movies Music Pictures Sites

$ echo "$myvar"
Desktop
Documents
Downloads
Movies
Music
Pictures
Sites

To get the first line of something, head -n1 works perfectly. It depends on your requirements and the possible values whether that is actually what you need.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.