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

Handbrake can’t access my video files

2  Asked on February 12, 2021 by roger06

   

Ubuntu on Hyper-V sluggish/slow UI experience

0  Asked on February 12, 2021 by bartek

       

Dell XPS 15 9570 – How to control the fans?

3  Asked on February 12, 2021 by j-ehrling

       

Freedesktop.org Failure

2  Asked on February 11, 2021 by garry-wakely

     

HP Pavillion x2 10.1 detachable

1  Asked on February 11, 2021 by daman-boparai

 

Stuck in emergency mode 20.10

0  Asked on February 11, 2021 by raj-verma

 

How to find /etc/apt/sources.conf file

2  Asked on February 11, 2021

 

Ubuntu 20.04 ImportError: No module named gtk.glade

1  Asked on February 10, 2021 by kyeiv

     

Can’t install software using package manager

0  Asked on February 10, 2021 by rachid-bensaleh

 

(Ubuntu 20.04) Port forwarding for Minecraft server

0  Asked on February 10, 2021 by mason-spies

 

Both Internet and Wifi not working on Ubuntu 20.04

0  Asked on February 10, 2021 by maxclac

   

Bluetooth doesn’t work anymore

0  Asked on February 9, 2021 by gogo94210

     

Multiple Partitions under /home and mount it as /home

0  Asked on February 9, 2021 by sriram-rayadurg

 

Installing Ubuntu on a new computer

1  Asked on February 9, 2021 by wassap124

     

Mouse sensitivity reset after replugging

0  Asked on February 8, 2021 by lehdari

         

Media keys running gnome-session-quit

0  Asked on February 8, 2021 by pineapplefan

     

(gedit:76): Gtk-WARNING

2  Asked on February 8, 2021 by manish-kumar

         

Ask a Question

Get help from others!

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