How to print linux group names on multiple line instead of single line output

In response to the comment by @Chris that

This only works for groups without spaces in the names!

I should mention that the accepted solution by @c4f4t0r and the solution by @bibi will work in most cases. I am running Cygwin, and the Windows part of the equation is probably why I hit this problem more often. Still, a group could be made with non-standard characters in normal Linux (I think), so I'll give the solution for group names with spaces. Spaces always make life fun!

I'll quickly give an example where spaces cause a problem. To see the group names with spaces, we look at the entire output of id

$ id
uid=1(me) gid=545(Users) 
groups=545(Users),66049(CONSOLE LOGON),11(Authenticated Users),
4095(CurrentSession),66048(LOCAL)

(Note: I did make the output a little more pleasing to the eye here on StackOverflow.)

From this, we see that the groups are {'Users', 'CONSOLE LOGON', 'Authenticated Users', 'CurrentSession', 'LOCAL'}

We can see the problem with the accepted solution in this case.

$ echo "groups:" ; for i in $(id -Gn);do echo "  - $i" ;done
    groups:
      - Users
      - CONSOLE
      - LOGON
      - Authenticated
      - Users
      - CurrentSession
      - LOCAL

A couple of groups get their names split up. To get the output we want, we need to use the id command, which takes a --zero ( -z ) flag. For more details on all the flags passed to id, see here.

$ man id | grep -A 1 "\-\-zero"
       -z, --zero
              delimit entries with NUL characters, not whitespace;

Our approach will need to be a bit different to those given above, but follow a lot of the same principles:

$ echo "groups:"; printf "%s" "  - "; id -Gnz | \
awk 'BEGIN{FS="\0"; OFS="\n  - "}{NF--; print}'
groups:
  - Users
  - CONSOLE LOGON
  - Authenticated Users
  - CurrentSession
  - LOCAL

The reason that we have a slightly-more-complicated awk is that there is always a trailing NUL, which we do not want in this case. The \ allows me to continue onto the next line with the same command, making things easier to read. The command is equivalent to:

$ echo "groups:"; printf "%s" "  - "; id -Gnz | awk 'BEGIN{FS="\0"; OFS="\n  - "}{NF--; print}'

From what I see, you are trying to convert the groups of your user to an yaml array, try to use:

echo "groups:" ; for i in $(id -Gn myuser);do echo "  - $i" ;done

groups:
  - users
  - lp
  - vboxusers
  - kvm

You can use too:

echo "groups: [ $(groups myuser | sed -e 's/.\+\s\+:\s\+\(.\+\)/\1/g' -e 's/\(\s\+\)/, /g') ]"

groups: [ myuser, lp, vboxusers, kvm ]

using bash:

for i in `groups`; do echo $i; done

using tr:

groups | tr \  \\n

Tags:

Linux

Unix

Sed

Yaml