Gerardo agustin Riera
Gerardo agustin Riera

Reputation: 133

Shell script linux, validating integer

This code is for check if a character is a integer or not (i think). I'm trying to understand what this means, I mean... each part of that line, checking the GREP man pages, but it's really difficult for me. I found it on the internet. If anyone could explain me the part of the grep... what means each thing put there:

echo $character | grep -Eq '^(\+|-)?[0-9]+$'

Thanks people!!!

Upvotes: 0

Views: 1073

Answers (2)

csikos.balint
csikos.balint

Reputation: 1105

I like this cheat sheet for regex:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

It is very useful, you could easily analyze the

'^(+|-)?[0-9]+$'

as

  • ^: Line must begin with...
  • (): grouping
  • \: ESC character (because + means something ... see below)
  • +|-: plus OR minus signs
  • ?: 0 or 1 repetation
  • [0-9]: range of numbers from 0-9
  • +: one or more repetation
  • $: end of line (no more characters allowed)

so it accepts like: -312353243 or +1243 or 5678
but do not accept: 3 456 or 6.789 or 56$ (as dollar sign).

Upvotes: 1

anubhava
anubhava

Reputation: 785108

Analyse this regex:

'^(\+|-)?[0-9]+$'

^ - Line Start
(\+|-)? - Optional + or - sign at start
[0-9]+ - One or more digits
$ - Line End

Overall it matches strings like +123 or -98765 or just 9

Here -E is for extended regex support and -q is for quiet in grep command.

PS: btw you don't need grep for this check and can do this directly in pure bash:

re='^(\+|-)?[0-9]+$'
[[ "$character" =~ $re ]] && echo "its an integer"

Upvotes: 4

Related Questions