TransWikia.com

Adding if statement to an existing while loop

Ask Ubuntu Asked by Malin on November 1, 2020

I have to do add an if statement to my while loop.

When I write ./scriptname 1, it executes my while loop.
When I instead write ./scriptname hello, it still executes my while loop.

What I want it to do is echo "no" if I add letters after ./scriptname but execute the while loop if I add numbers after ./scriptname.

Does anyone know what I have done wrong in the script attached?

enter image description here

One Answer

Its a good practice to keep your if-then-statement as short as possible, this way you dont need the else statement.

#!/bin/bash

x=$1
y=$2

if [[ $x =~ (^$|[^0-9]) ]]; then
    echo "no"
    exit 0
fi
while (( $x <= 3 )); do
    echo "$x $y"
    ((x++))
    sleep 5
done

Or with a for-loop:

for ((z=3; $x<=$z; x++)); do
    echo "$x $y"
    sleep 5
done

Answered by bac0n on November 1, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP