views:

56

answers:

2

I found a script which has the following snippet:-

userid=`expr "\`id\`" : ".*uid=[0-9]*(\(.[0-9a-z]*\)) .*"`

It returns the userid.

When i tried to learn how it is doing:-

#id
#uid=11008(adilm) gid=1200(cvs),1400(build)

So I realized that (.[0-9a-z]*) is matching the userid. But if I placed like below:

#userid=`expr "uid=11008(ADILM) gid=1200(cvs),1400(build)" : ".*uid=[0-9]*(\(.[0-9a-z]*\)) .*"`
#echo $userid
ADILM

It works. As per my understanding '.' is matching to ADILM. But when i removed '.' like below:-

#userid=`expr "uid=11008(ADILM) gid=1200(cvs),1400(build)" : ".*uid=[0-9]*(\([0-9a-z]*\)) .*"`
#echo $userid
ADILM

It still works how? We have only provided lowercase letters but its still working.

+1  A: 

this will not explain the regex, but alternative ways to get your id.

$ id -u -n

$ id|sed 's/uid=[0-9]*(//;s/).*//'
ghostdog74
+3  A: 
  • The subexpression (\(.[0-9a-z]*\)) matches a group containing the brackets plus the user id.
  • The dot inside this regex matches only the first character and all others need to be lowercase or numeric anyway.
  • So obviously the regex here is not case sensitive (i option) per default. As your username is only [a-z0-9] it still matches.
  • I don't think the dot makes sense. Are there any valid usernames not starting with a letter? The dot is here to make sure the username is at least one character long.
  • Better might be (\([0-9a-z]+\)) then.
Peter Kofler
How to make it case sensitive in expr?
Adil
@Peter i read that "The : operator can substitute for match." I tried `expr match "uid=11008(ADILM) gid=gid=1200(cvs),1400(build)" ".*uid=[0-9]*(\(.[0-9a-z]*\)) .*"` but its not working. It seems match is case sensitive but : is case insensitive (opposed to mentioned in man page and guides)
Adil
Has to be something like that. I don't know shell that well.
Peter Kofler