Bash脚本开发求助:如何修改脚本以正确显示用户所属组的用户名信息
Fixing Your Shell Script to Show User and Group Membership
Hey there! Let's work through fixing this script together—you're already on the right track, just a few key tweaks are needed to get it working as expected.
First, Let's Break Down the Issues in Your Original Script
Your current code has a couple of critical problems that are blocking it from showing the username correctly:
- The
GroupsOfUserfunction doesn't accept or use the parameter you passed (/etc/group/passwd—that path is also incorrect, since/etc/passwdand/etc/groupare separate system files for user and group data). - Running
groupswithout a username argument returns your current user's groups, not the target user's you want to check. - The
echostatement has an empty$()placeholder, so no username value gets inserted, and the output order is reversed from what you need.
Here's the Corrected Script
GroupsOfUser() { # Check if a username was provided when calling the function if [ -z "$1" ]; then echo "Oops! Please provide a username. Usage: GroupsOfUser <username>" return 1 fi # Store the target username in a variable for easy reuse local target_user="$1" # Fetch and clean up the list of groups the user belongs to # The `groups` command outputs like: "user : group1 group2 group3" # We extract everything after the colon, then trim extra spaces local user_groups=$(groups "$target_user" | cut -d ':' -f 2 | xargs) # Loop through each group and print the required format for group in $user_groups; do echo "$target_user is part of the group $group" done } # Example: Call the function with a username (replace "mohamed" with your target user) GroupsOfUser "mohamed"
How This Works (Step by Step)
- Parameter Check: The script first verifies you provided a username. If not, it shows a friendly usage prompt to avoid confusion.
- Store Username: We save the input username to a variable (
target_user) so we can easily reference it throughout the script. - Fetch & Clean Groups: The
groups "$target_user"command pulls all groups the user belongs to. We usecutto remove the username prefix (everything before the colon) andxargsto clean up extra spaces, leaving a neat space-separated list of groups. - Loop & Output: We iterate over each group in the list and print the exact format you requested:
<username> is part of the group <group>.
Testing the Script
To test it, just replace "mohamed" in the final line with any valid username on your system (like root or your own username). You'll see output like:
mohamed is part of the group mohamed mohamed is part of the group adm mohamed is part of the group sudo
内容的提问来源于stack exchange,提问作者Mohamed ali Lemkecher
相关产品推荐
相关产品推荐

