Skip to main content
Solved

Using DSCL to Create an Array of Admin Users


Forum|alt.badge.img+4

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")

Best answer by ChrisCox

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 original
Did this topic help you find an answer to your question?

2 replies

Forum|alt.badge.img+7
  • Contributor
  • 29 replies
  • Answer
  • February 18, 2020

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

Forum|alt.badge.img+4
  • Author
  • Contributor
  • 16 replies
  • February 18, 2020

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


Reply


Cookie policy

We use cookies to enhance and personalize your experience. If you accept you agree to our full cookie policy. Learn more about our cookies.

 
Cookie settings