Linux Classroom Series – 03/Sept/2020

Iterating through directories and files

  • To do this we can write a very simple for loop
  • Exercise: Find mistake in the following shell script
#!/bin/bash
echo "Directory path entered by user is /home/ubuntu/contents/*"
for path in "/home/ubuntu/contents/*";
do
    echo "processing ${path} "
    if [ -d "$path" ];
    then
        echo "${path} is directory"
    elif [ -f "$path" ];
    then
        echo "$path is file"
    fi
done

  • where as this script is working
for file in /home/ubuntu/contents/*; do
        echo $file
done


  • Try to find a way to reuse last commands output

  • Nesting loops

#!/bin/bash
for (( row=1; row<=3; row++ ))
do
    
    for (( col=1; col<=3; col++ ))
    do
        echo "${row} * ${col}"
    done
done

  • Redirecting loop output to a file
#!/bin/bash
for (( row=1; row<=3; row++ ))
do
    
    for (( col=1; col<=3; col++ ))
    do
        echo "${row} * ${col}"
    done >> rowscols.txt
done

While and until

  • Example of while
$COUNT=20
while [ $COUNT -gt 0 ] ; 
do
    echo "$COUNT"
    (( COUNT-- ))

done;

  • Another example for same logic
#!/bin/bash
COUNT=20
while [ "$COUNT" -gt 0 ] ; 
do
    echo "$COUNT"
    (( COUNT-- ))

done;

  • Example Until loop
#!/bin/bash
COUNT=10
until (( COUNT < 0 )); do
    echo "$COUNT"
    (( COUNT-- ))
done

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin