script problem

Hi All

In a script (ksh), I want a user to enter 4 characters, these can be a mix of letters (uppercase and lowercase) and numbers.

In this example $var represents what the user has entered.

eg $var can be A9xZ, 3DDL, bbHp .........etc

I need to check that the user has only entered characters so I added the following code:

# Check for invalid characters
echo "$var" | grep [^a-zA-Z0-9] >/dev/null
if [ $? -eq 0 ]
then
echo "$var is not valid."
fi

This appears to work ok unless the user enters a wildcard character.

For example if the user enters bin*, the script expands the * and makes $var equal to all files in the current directory which start with bin.

So $var is "bin bindir binary"

My question is how can I process $var literally as "bin*" in the above grep statement?

Thanks for your help
Helen
:confused:

try grep [^a-zA-Z0-9 add your list of metacharictures here]

Hello Helen,

echo "$var" | grep [^a-zA-Z0-9] >/dev/null
will return a 0 if $var is "bin*" because the grep is only serching for alphabetic characters and numbers.

Plus if you do: echo "$var"
This will return: bin*

However, if you do(without quotes): echo $var
This will return: bin binary ....

If you do want * to be a valid character you can put a (backslash) \ before it in the grep statement. This turns off any special meanings of such characters.

Hope this answers your question.
Regards

You should forget about grep anyway. ksh can do this all by itself without invoking an external program. Try:

if [[ $var = +([a-zA-Z0-9]) ]] ; then
        echo $var is ok
else
        echo $var is an error
fi

Note that you must use the double bracket not the single bracket.

Thanks for all your help on this :wink: