1. Getting a shell with the new group without logging out and in again
If you're only adding one group, I used the following:
exec sg <new_group_name> "newgrp `id -gn`"
This is a variation on Legooolas's two-layer newgrp trick, but it is in one line and doesn't require you to manually enter your primary group.
sg
is newgrp but accepting a command to execute with the new group ID. The exec
means that the new shell replaces the existing shell, so you don't need to "logout" twice.
Unlike using su, you don't need to type in your password. It also doesn't refresh your environment (other than adding the group), so you retain your current working directory etc.
2. Executing the command in all Screen windows in a session
The at
command in Screen runs a command in whatever windows you specify (note this is a Screen command, not a shell command).
You can use the following command to send the command to all an existing Screen sessions:
screen -S <session_name> -X at \# stuff 'exec sg <new_group_name> "newgrp `id -gn`"^M'
Note the use of single quotes to preserve the backticks and get id
to run in the Screen session, and the ^M to get Screen to hit 'enter' at the end of your command.
Note also that screen's stuff
command simply types the command text on your behalf. Therefore something strange may happen if one of the screen windows has a half-written command at a command prompt or is running an application other than a shell (e.g. emacs, top). If this is an issue, I have some ideas:
- To get rid of any half-written command, you can add "^C" to the start of the command.
- To avoid running the command in an emacs window, etc, you could ask
at
to filter on window title etc (in the example above, I use "#", which matches all windows, but you can filter by window title, user, etc).
To run the command in a specific window (identified by window number), use the following:
screen -S <session_name> -p 0 -X stuff 'exec sg <new_group_name> "newgrp `id -gn`"^M'