DEV Community

Discussion on: Let's progress together with the Linux Shell

Collapse
 
vlasales profile image
Vlastimil Pospichal
PERCENTAGE=$(($INDEX * 100 / $TOTAL))
Collapse
 
aminnairi profile image
Amin

Hi Vlastimil and thanks for you comment.

Yes indeed, it is possible to do more complex operations inside these double parenthesis construct, which is really cool!

Unfortunately, when dealing with numbers, this construct will not return decimal numbers as we might expect.

#!/usr/bin/sh

INDEX=0
TOTAL=12

for operation in $(seq $INDEX $(( TOTAL - 1 )))
do
    PERCENTAGE=$(( INDEX * 100 / TOTAL ))

    echo "Backing up folders (${PERCENTAGE}% done)"

    (( INDEX++ ))
done

echo "Backup done."

This means running this script will give us this output.

Backing up folders (0% done)
Backing up folders (8% done)
Backing up folders (16% done)
Backing up folders (25% done)
Backing up folders (33% done)
Backing up folders (41% done)
Backing up folders (50% done)
Backing up folders (58% done)
Backing up folders (66% done)
Backing up folders (75% done)
Backing up folders (83% done)
Backing up folders (91% done)
Backup done.

In that case this works, but I wanted to have some decimal places for my percentage so it is not very useful here. But in any other cases where the decimal places are not mandatory I would use your version anytime since it does not rely on any other external program like bc. We could even have used python instead of bc if you are more confortable with Python (but it requires it to be installed, which is often the case on most installations)!

#!/usr/bin/sh

INDEX=0
TOTAL=12

for operation in $(seq $INDEX $(( TOTAL - 1 )))
do
    PERCENTAGE=$(python3 -c "print(round($INDEX / $TOTAL * 100, 2))")

    echo "Backing up folders (${PERCENTAGE}% done)"

    (( INDEX++ ))
done

echo "Backup done."

# Backing up folders (0.0% done)
# Backing up folders (8.33% done)
# Backing up folders (16.67% done)
# Backing up folders (25.0% done)
# Backing up folders (33.33% done)
# Backing up folders (41.67% done)
# Backing up folders (50.0% done)
# Backing up folders (58.33% done)
# Backing up folders (66.67% done)
# Backing up folders (75.0% done)
# Backing up folders (83.33% done)
# Backing up folders (91.67% done)
# Backup done.