Writing a file using a different group in Linux
I have a user id that works under multiple groups like sysgroup, usergroup. When I write to another default user directory, it writes to sysgroup. But for some users, I need to write with group permission. How can I figure this out?
Here is my sample code
if ls n18_????_??????????.txt &> /dev/null; then
cp n18_????_??????????.txt /export/home/user
chgrp usergroup /export/home/user/n18_????_??????????.txt
mv n18_????_??????????.txt $archDir
fi
I copy and then change the group, so every time it changes the group for all files that match the pattern.
source to share
The command install
allows you to copy a file by specifying the destination file ownership and permissions.
By the way, you can avoid parsing the ls
output , although I'm not sure what would be the most idiomatic solution. It is often a bad idea to simply ignore any error messages, but perhaps the easiest one here. (This means that you will not be notified, for example, if you are running out of permissions!)
install --group usergroup n18_????_??????????.txt /export/home/user 2>/dev/null &&
mv n18_????_??????????.txt "$archDir"
Note that there is a race condition here. If new files matching the pattern may appear at runtime install
, mv
delete them even if they were not copied. If you can use the Bash -only constructors, try this:
list=( n18_????_??????????.txt ) # Expands the wildcard only once
if [ -e "${list[0]}" ]; then
install --group usergroup "${list[@]}" /export/home/user &&
mv "${list[@]}" "$archDir"
fi
This is ideal because it will show warnings or error messages as long as they work quietly normally.
source to share
SG
Another way is to use sg
:
sg usergroup bash
It calls another shell that the active group is in usergroup
. When you exit, it goes back to the original.
usermod
You can also use usermod
to change the main user group. This makes it the default on every login.
usermod -g usergroup user
Sudo
Another way is to use sudo
. See also this topic.
sudo -g usergroup id -gn ## Verify that it works.
sudo -g usergroup bash
Solution for scripts
You can call the script call again with sudo
.
#!/bin/bash
if [[ $1 == __GROUP_CHANGED__ ]]; then
shift
else
exec /usr/bin/sudo -g users "$0" __GROUP_CHANGED__ "$@"
fi
or
#!/bin/sh
if [ "$1" = __GROUP_CHANGED__ ]; then
shift
else
exec /usr/bin/sudo -g users "$0" __GROUP_CHANGED__ "$@"
fi
The concept can also work with sg
, but sg
does not accept raw arguments for the command. It only takes one string argument and passes it to /bin/sh
. This is not a good technique to use when you are passing multiple arguments, especially those with spaces, to your script. And quoting is a big no.
source to share