Results 1 to 5 of 5
I want to write a script to check if the command line has arguments. If it doesn't it will issue an error msg.
If the script is run with an ...
- 03-04-2009 #1Just Joined!
- Join Date
- Feb 2009
- Posts
- 9
Loop to check if command line arguments are even or odd numbered....HELP!
I want to write a script to check if the command line has arguments. If it doesn't it will issue an error msg.
If the script is run with an argument say " /home>script.bash 2"
it will then run through a loop to check if the number is even or odd.
If its even it will print a msg and exit. If its odd, it will prompt the user to re-enter an even number.
Here is where I am stuck, once the user enters in a new number I want the script to then check if its even or odd, if it is odd I want it to loop until an even number is entered.
This is what I have so far, for the most part it works. Just the last stage to have the user re-enter a number then loop if its odd... doesn't work
Any help is much appreciated.
#!/bin/bash
if [ $# -le 0 ]; then
echo "USAGE: $0 [number]" >&2
exit 1
fi
for x
do
out=$(( $x % 2 ))
if [ $out -eq 0 ]
then
echo "The EVEN number is: $x"
exit 1
fi
echo "Number is NOT even..."
read -p "Please enter an EVEN numer:" num
echo "The EVEN number is: $num"
done
Thanks.
- 03-04-2009 #2Just Joined!
- Join Date
- Feb 2009
- Posts
- 45
Thereʼre a couple of comments I have on this piece of code:
Originally Posted by IbuntYOU
- Please use CODE tags.
- Somewhere in this code an actual loop is missing. There really is no loop. The
construct loops through all the CLI arguments of the script, which, in your case of a single parameter, is not a loop. Maybe you wanted to place the loop somehwere in the last echo-read-echo block?Code:for x; do […] done
- Every variable inside of a "$(( … ))" construct is evaluated once. So "$(( x % 2))" is fine.
- 03-04-2009 #3Just Joined!
- Join Date
- Feb 2009
- Posts
- 9
Hey,
Thanks for the reply, but I am still a little lost as to how and where to run the loop. Do I need a while?
How do i set it up so the last section just loops until an even number is re-entered?
thanks.
- 03-04-2009 #4Just Joined!
- Join Date
- Feb 2009
- Posts
- 45
Most certainly.
Originally Posted by IbuntYOU
Well, this would be a solution (though it doesnʼt protect against illegal input like letters or the like):
Originally Posted by IbuntYOU
Code:[…] num=1; while [ "$((x % 2))" -eq 1 ]; do echo "Number is NOT even…"; read -p "Please enter an EVEN number: " num; done exit 1; […]
- 03-08-2009 #5Just Joined!
- Join Date
- Feb 2009
- Posts
- 9


Reply With Quote
