Question

Echo "Hello everybody!"

I need to check whether the input argument of a linux script does comply with my security needs. It should contain only a-z characters, 0-9 digits, some spaces and the "+" sign. Eg.: "for 3 minutes do r51+r11"

This didn't worked for me:

if grep -v '[0123456789abcdefghijklmnopqrstuvwxyz+ ]' /tmp/input; then
  echo "THIS DOES NOT COMPLY!";
fi

Any clues?

Was it helpful?

Solution

You are telling grep:

Show me every line that does not contain [0123456789abcdefghijklmnopqrstuvwxyz+ ]

Which would only show you lines that contains neither of the characters above. So a line only containing other characters, like () would match, but asdf() would not match.

Try instead to have grep showing you every line that contains charachter not in the list above:

if grep '[^0-9A-Za-z+ ]' file; then

If you find something that's not a number or a letter or a plus, then.

OTHER TIPS

You want to test the entire row (assuming there is only one row in /tmp/input), not just whether a single character anywhere matches, so you need to anchor it to the start end end of the row. Try this regexp:

^[0123456789abcdefghijklmnopqrstuvwxyz+ ]*$

Note that you can shorten this using ranges:

^[0-9a-z+ ]*$

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top