Bash script while loop

Bash script while loop is one of the most fundamental and powerful constructs computing because it allows us to repeat a set of commands, as many times as we want, upon a list of items of our choosing. The loop is how we make the computer do that repetitive work

#!/bin/bash
# while-read: read lines from a file
while read ; do
printf "%s\n" $REPLY
done < /etc/passwd

while-loop is a variation of the above, but is safer for reading lines from a file:

while read url
do
  curl "$url" >> everywebpage_combined.html
done < list_of_urls.txt

A while loop with interactive

MacBook-Pro:~ sysadmin$ ls *.sh| while read i; do echo $i ; done

or in .sh file

ls *.sh | while read f ; do
  echo "$f"
done

 


Also published on Medium.

1 Reply to “Bash script while loop”

  1. #!/bin/bash
    src_conf="/root/community-os/solr/6.x/"
    echo $src_conf
    ls /var/solr/data/|grep nightly | while read f ; do
    echo "/var/solr/data/$f/"
    rsync -arvz $src_conf "/var/solr/data/$f/conf/"
    done

Leave a Reply

Your email address will not be published. Required fields are marked *