AnswerBun.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!

Related Questions

Ubuntu menu won’t close after opening

0  Asked on January 27, 2021 by shadowblitz16

   

How do I install Psiphon on Ubuntu 14.04 LTS (Step by Step)

4  Asked on January 25, 2021 by rahul-raj-rai

 

How to limit user access to selected applications?

2  Asked on January 25, 2021 by jorrit

       

kernel panic-not syncing: VFS: unable to mount root fs on unknown block(0,0)

1  Asked on January 24, 2021 by donttakemeseriously

     

How to torrify the Ubuntu host?

0  Asked on January 23, 2021 by k-madhura-nadh-12a

         

Mouse work ONLY after suspend

0  Asked on January 23, 2021 by idir

 

“cannot find -lmpi*” when compiling openmpi code

3  Asked on January 22, 2021 by thomas-ding

     

Ask a Question

Get help from others!

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