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
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
I came across an article on StackOverflow where the solution was presented. Which by the way is surprisingly easy:
$ echo "$output" | wc -l
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.
No comments yet.
Personal Internet VMware PHP Linux Shell Bluecoat Proxy Windows Hardware Virtualization Nagios MySQL DB Monitoring Mail Android Network Wyse Hacks Tomcat Postgres Apple Mac Surveillance Backup BSD ZFS Solaris SmartOS Unix Multimedia Perl Database MongoDB CMS OTRS FreeBSD Wordpress LXC Nginx Proxmox DNS Graphics GlusterFS Security Chef HAProxy Icinga Ansible HTML MariaDB Containers Rancher Docker AWS ELK Kibana Logstash Filebeat Varnish PGSQL PostgreSQL ElasticSearch CouchDB Bash Macintosh Container Minio Grafana InfluxDB Databases NFS OSSEC SystemD Java Zoneminder Elasticsearch SSL TLS Icingaweb2 Cloud Wireless Kubernetes Ubuntu