3

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)
5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy