Hello All,
My apologies if a similar question has already been posted. I searched for "grep", "egrep" and "null"
I'm having an issue with egrep and an extended regular expression.
I'm doing a test for a job name. I would like to have the user enter a job name with no spaces and also test to make sure that they don't accidently hit the return key too fast.
My code:
echo "Please enter a job name (no spaces): "
read jobname
# ***test not working*** while [`echo $jobname | egrep '(" "|"^$")' | wc -l -gt 0 ]; do
while [`echo $jobname | grep " " | wc -l -gt 0 ] || [`echo $jobname | grep "^$" | wc -l -gt 0 ]; do # working
echo "Please enter a new job name (NO spaces): "
read jobname
done
The command egrep '(" "|"^$")' isn't working!!! It doesn't give any errors but it never goes through the while statement from any test.
Thanks in advanced!!
It is safer to have while not followed by the "okay" expression.
The following ensures there is only and at least one non-blank characters:
while ! echo "x$jobname" | egrep '^x[^[:blank:]]+$' >/dev/null
do
echo "Please enter a new job name (NO spaces): "
read jobname
done
The quotes are necessary for safety. Also further references should quote "$jobname".
The x is for additional safety, e.g. to escape a user input "-n" that has a special meaning in echo.
More strict is to test for at least one alphanumeric character:
while ! echo "x$jobname" | egrep '^x[[:alnum:]]+$' >/dev/null
#! /bin/bash
echo "Enter job name:"
read x
while [ 1 ]
do
echo $x | egrep -q "^$|^ *$"
if [ $? -eq 0 ]
then
echo "No blank lines or spaces. Enter job name:"
read x
else
break
fi
done
echo $x
while [`echo $jobname | egrep '^[^[:blank:]]+$' | wc -l -gt 0 ]; do
MadeInGermany: I'm unaware of what the "x" in your example does. I'm not asking for a long winded explanation, although you may. If you don't mind give me a viable resource where I may read up on that functionality!
balaisuri: thanks for helping. I did try the ERE of "^$|^ *$" and it didn't work at least not on my system. it catches null but doesn't catch a line with a space.
Corona688: Thanks for the many responses. I'll have to wait till I have more time to go through your methods.
That's way too convoluted. It may "work", but it's too confusing to put into long-term source code. And it is grammatically incorrect, as I pointed out before. I would look at the other suggestions that were made, as you indicated you want to do.