Why -while read line- does not work with stdout

Written by - 0 comments

Published on - Listed in Linux Shell Coding


For some reason I was stuck in further developing of check_equallogic because of one little bugger: I couldn't get shell outputs (several lines) into one array. This has been frustrating since it didn't make any sense to me, why Bash wouldn't correctly read the lines into an array. Until I understood. My mistake:

i=1 cat /etc/resolv.conf | while read line; do myarray[$i]=$line; (( $i+1 )); done

It might seem correct - but it isn't. Thanks to this forum topic I finally understood that 'while' opens its own shell and is not able to read the values: The while statement is part of a pipeline and runs in its own shell so the array value is not available to the main script.. So the solution is done with a for loop (why didn't I think of that before, ouch!):

i=0 for line in $(cat /etc/resolv.conf); do myarray[${i}]=$line; i=$(($i + 1 ));done

And that's actually why I love working in the IT sector: You never finish to learn (= it never get's boring)!


Add a comment

Show form to leave a comment

Comments (newest first)

No comments yet.

RSS feed

Blog Tags:

  AWS   Android   Ansible   Apache   Apple   Atlassian   BSD   Backup   Bash   Bluecoat   CMS   Chef   Cloud   Coding   Consul   Containers   CouchDB   DB   DNS   Database   Databases   Docker   ELK   Elasticsearch   Filebeat   FreeBSD   Galera   Git   GlusterFS   Grafana   Graphics   HAProxy   HTML   Hacks   Hardware   Icinga   Influx   Internet   Java   KVM   Kibana   Kodi   Kubernetes   LVM   LXC   Linux   Logstash   Mac   Macintosh   Mail   MariaDB   Minio   MongoDB   Monitoring   Multimedia   MySQL   NFS   Nagios   Network   Nginx   OSSEC   OTRS   Office   PGSQL   PHP   Perl   Personal   PostgreSQL   Postgres   PowerDNS   Proxmox   Proxy   Python   Rancher   Rant   Redis   Roundcube   SSL   Samba   Seafile   Security   Shell   SmartOS   Solaris   Surveillance   Systemd   TLS   Tomcat   Ubuntu   Unix   VMWare   VMware   Varnish   Virtualization   Windows   Wireless   Wordpress   Wyse   ZFS   Zoneminder