Bash need to test for alphanumeric string

Atomiklan picture Atomiklan · Aug 4, 2013 · Viewed 30.3k times · Source

Trying to verify that a string has only lowercase, uppercase, or numbers in it.

if ! [[ "$TITLE" =~ ^[a-zA-Z0-9]+$ ]]; then echo "INVALID"; fi

Thoughts?

* UPDATE *

The variable TITLE currently only has upper case text so it should pass and nothing should be outputted. If however I add a special character to TITLE, the IF statement should catch it and echo INVALID. Currently it does not work. It always echos invalid. I think this is because my regex statement is wrong. I think the way I have it written, its looking for a title that has all three in it.

Bash 4.2.25

The idea is, the user should be able to add any title as long as it only contains uppercase, lowercase or numbers. All other characters should fail.

* UPDATE *

If TITLE = ThisIsAValidTitle it echos invalid.

If TITLE = ThisIs@@@@@@@InvalidTitle it also echos invalid.

* SOLUTION *

Weird, well it started working when I simplified it down to this:

TEST="Valid0"
if ! [[ "$TEST" =~ [^a-zA-Z0-9] ]]; then
  echo "VALID"
else
  echo "INVALID"
fi

* REAL SOLUTION *

My variable had spaces in it... DUH

Sorry for the trouble guys...

* FINAL SOLUTION *

This accounts for spaces in titles

if ! [[ "$TITLE" =~ [^a-zA-Z0-9\ ] ]]; then
  echo "VALID"
else
  echo "INVALID"
fi

Answer

Ansgar Wiechers picture Ansgar Wiechers · Aug 4, 2013

I'd invert the logic. Test for invalid characters and echo a warning if at least one is present:

if [[ "$TITLE" =~ [^a-zA-Z0-9] ]]; then
  echo "INVALID"
fi

With that said, your original check worked for me, so you probably need to provide more context (i.e. a larger portion of your script).