Skip to content
Advertisement

How to get user from init bash script Linux(before user session created)

At Debian im trying to change specific directory ownership after every reboot. But in my case it doesnt work, because user always set as root at reboot time. When i try this in terminal it works well (i think because myUser session created) but i need to change it at reboot time.

So far i refer this link but it fails for me : https://unix.stackexchange.com/questions/183183/using-chown-useruser-inside-bash-script

CURRENT_USER=$(who | awk ‘NR==1{print $1}’)
sudo chown -R $CURRENT_USER:$CURRENT_USER /myfile/foo

second way:

sudo chown -R ${USER:=$(/usr/bin/id -run)}:$USER /myfile/foo

i dont want to write like this :

sudo chown myUser:myUser /myfile/foo

Advertisement

Answer

Linux is a multiuser system. There can be more than one users logged in simultaneously or no one at all. Often there is no way to define something like a “default” user. There are however workarounds that you could use to find the “default” user if the machines are setup as typical single user company computers.

  • Take the user with UID 1000. If all the machines are setup so that the “default” user has UID 1000, you could just use this UID instead of the username in the chown command.
  • Look for the subdirectories of /home. Only standard (non-system) users have a home directory. On standard systems they are named with the username.

That beeing set: Your script will be highly dependent on the specific setup of the machines. Also there might be a less intrusive, less machine dependent and more secure solution to your problem. You could try to

  • leave root as owner of the directory but enable read and write permissions for other users.
  • set the sticky bit for the directory (just like /tmp).
  • make a new group that owns the directory and add the users to it.

The last option is actually used a lot. For example often web servers make their source directories owned by a group called www and users, that are allowed to read/write the data are added to that group. This also works well in real multiuser systems like servers or shared machines.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement