Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write File Using another group in Linux

Tags:

linux

shell

unix

I have an user id ops which comes under multiple groups like sysgroup,usergroup. When I write to some other user directory by default it is writing under sysgroup. But for some user I need to write with usergroup permission. How can I acheive this?

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 am copying then changing the group, So each time it changes the group for all the files matching the pattern.

like image 422
Rajeshkumar Avatar asked Mar 18 '23 18:03

Rajeshkumar


1 Answers

sg

Another way is to use sg:

sg usergroup bash

It summons another shell in which the active group is usergroup. It gets back to the original if you exit.

usermod

You can also use usermod to change the primary group of the user. It makes it the default in every login.

usermod -g usergroup user

See sg and usermod.

sudo

Yet another way is to use sudo. See this thread too.

sudo -g usergroup id -gn  ## Verify that it works.
sudo -g usergroup bash

Solution for scripts

You can make the script call itself 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 may also work with sg but sg does not accept raw arguments for the command. It only accepts a single string argument and pass it to /bin/sh. It's not a good method to use when you're passing multiple arguments especially those with spaces to the script. And quoting is a big no.

like image 173
konsolebox Avatar answered Mar 25 '23 10:03

konsolebox