Using DSCL to Create an Array of Admin Users

mcgace
New Contributor III

Hi guys,

I am using dscl . read to create an array with users in the Admin Group. However, its not giving me what I want.

I want each user in the Admin Group to be a separate element in the array. How do I do that? I tried using cut -d " " but that didn't work

#Users Array - All users in Admin group
USERS=$( dscl . -read Groups/admin GroupMembership | cut -c 18- )

Output: USERS=([0]="root admin1 admin2")

Desired Output: USERS=([0]="root" [1]="admin1" [2]="admin2")

1 ACCEPTED SOLUTION

ChrisCox
New Contributor III

You have to surround the variable with parentheses when declaring an array. Also, since you know the first element before the first IFS (space) is always going to be "GroupMembership:", you could just include every element beyond the first with awk This should work:

# Build an array of all group members of the admin group. Use awk to truncate the first field.
USERS=($(/usr/bin/dscl . read /Groups/admin GroupMembership | /usr/bin/awk '{print substr($0,index($0,$2))}'))

# Verify the array is built properly
for i in "${USERS[@]}"; do
    echo "User: $i"
done

View solution in original post

2 REPLIES 2

ChrisCox
New Contributor III

You have to surround the variable with parentheses when declaring an array. Also, since you know the first element before the first IFS (space) is always going to be "GroupMembership:", you could just include every element beyond the first with awk This should work:

# Build an array of all group members of the admin group. Use awk to truncate the first field.
USERS=($(/usr/bin/dscl . read /Groups/admin GroupMembership | /usr/bin/awk '{print substr($0,index($0,$2))}'))

# Verify the array is built properly
for i in "${USERS[@]}"; do
    echo "User: $i"
done

mcgace
New Contributor III

Thanks @ChrisCox thats exactly what I needed. I now have an array that I can I can loop through each user.