Header RSS Feed
 
If you only want to see the articles of a certain category, please click on the desired category below:
ALL Android Backup BSD Database Hacks Hardware Internet Linux Mail MySQL Monitoring Network Personal PHP Proxy Shell Solaris Unix Virtualization VMware Windows Wyse

Bash: Why is a multi-line output saved as one line in a variable?
Monday - Mar 26th 2018 - by - (0 comments)

Let's start off with the response to this question (Why is a multi-line output saved as one line in a variable?): It's not!

As I'm currently improving the monitoring plugin check_couchdb_replication, I came across a little problem.

I wanted to check the number of lines of a curl output. By simply using the curl command directly, I got 29 lines in return:

$ curl -q -s localhost:5984/_scheduler/docs/_replicator -u admin:secret  | wc -l
29

But when I saved the command's output in a variable, the whole output seems to have merged into one line:

$ output=$(curl http://localhost:5984/_scheduler/docs/_replicator -u admin:secret)
$ echo $output | wc -l
1

I came across an article on StackOverflow where the solution was presented. Which by the way is surprisingly easy:

$ echo "$output" | wc -l
29

By simply putting the variable into double-quotes, the correct number of lines is shown again. But why is that? In the same article linked above, the explanation from Jonathan Leffler is really good:

the difference is that (1) the double-quoted version of the variable (echo "$VARIABLE") preserves internal spacing of the value exactly as it is represented in the variable — newlines, tabs, multiple blanks and all — whereas (2) the unquoted version (echo $VARIABLE) replaces each sequence of one or more blanks, tabs and newlines with a single space. Thus (1) preserves the shape of the input variable, whereas (2) creates a potentially very long single line of output

Quite crazy that after more than 10 years of bashing I only came across this today.

 

Add a comment

Show form to leave a comment

Comments (newest first):

No comments yet.

Go to Homepage home
Linux Howtos how to's
Monitoring Plugins monitoring plugins
Links links

Valid HTML 4.01 Transitional
Valid CSS!
[Valid RSS]

7028 Days
until Death of Computers
Why?