Posted on 02-18-2020 03:19 AM
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")
Solved! Go to Solution.
Posted on 02-18-2020 05:38 AM
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
Posted on 02-18-2020 05:38 AM
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
Posted on 02-18-2020 07:44 AM
Thanks @ChrisCox thats exactly what I needed. I now have an array that I can I can loop through each user.