Loops

  • Iteration structures.

  • Tied to comparisons (in order to stop iterating)

    • for you know how many times it will iterating for list=$(ls /) for i in $ list do instructions done

    • while when you don't know how many times that the loop will be executed max=30 i=0 while [ $i -lt $max ] do echo $i i=$(($i+1)) done

#!/bin/bash

# example "for" to count directories and files in one route

if [ $# -eq 1]
then
    directories=0
    files=0
    input=$1
    for i in $(ls $input)
    do
        if [ -d $input/$i ]
        then
            directories=$(($directories + 1))
        fi
        elif [ -f $input/$i ]
        then
            files=$(($files + 1))
        fi
    done
else
    echo "Usage: bash for.sh input"
fi

echo "In $input there are $directories directories"
echo "In $input there are $files files"
#!/bin/bash

# example "while" counter

max=100
i=0

while [ $i -lt $max ]
do
    echo $i
    i=$(($i+1))
done
# example "while" password hasher

if [ $# -eq 1]
then
    filename=$1
    output=$2
    if [ -e $filename ]
    then
        while read line
        do
            echo -n $line | md5sum | cut -f -d' ' >> output.txt
        done < $filename
    else
        echo "Wrong file entered"
        exit
    fi
   
else
    echo "Usage: $0 <filneame> <output>"
    exit
fi

echo "In $input there are $directories directories"
echo "In $input there are $files files"

Last updated