Home > Blockchain >  script check all groups a user is part of in bash
script check all groups a user is part of in bash

Time:09-21

I want to write a shell script checking all the groups a user is part of and for each one display <username> is part of the group <group>. I did the script but it doesnt show me the users' names. Here is my script:

GroupsOfUser(){
    for i in $(groups)  ; do  
        echo "$i" "is part of" "$()"
    done 
}
GroupsOfUser '/etc/group/passwd'

What command should I add to the script so it shows me the user names of all the groups?

I am all new in programming and have been trying to find a solution for two days already.

CodePudding user response:

The system variable $USER contais the account name of the current user. Maybe also look at the id command.

for i in $(groups); do  
    echo "$USER is part of$i"
done

or more succinctly

printf "$USER is part of %s\n" $(groups)

The groups command alone is generally more useful; Unix utilities tend to print only the information you actually need, which makes it easier to use them to build more complex scripts (though there are common exceptions, like ps and df, and hence thousands of scripts which have to reinvent parsers for their output).

  •  Tags:  
  • bash
  • Related