0

I am creating a debian package where i have written preinst and post inst scripts. In my preinst scripts, am taking backup of some file using "sudo". But actual owner of these file are some other customized user. Hence when i take backup or restore these files then, user is changing to root.

How to define my custom user to copy or move files inside pre install script of debian package?

if [ -e /home/custom/file.txt]; then
    sudo cp -v /home/custom/file.txt /home/custom/backup/file.txt
    exit 1
fi

After executing above code in pre inst script, owner of file.txt changes to root

tripleee
  • 175,061
  • 34
  • 275
  • 318
Karma Yogi
  • 615
  • 1
  • 7
  • 18
  • Does this answer your question? [How to run script as another user without password?](https://stackoverflow.com/questions/6905697/how-to-run-script-as-another-user-without-password) – tripleee Jul 01 '21 at 08:33
  • The Debian installer already runs as root, so I can see no reason why you use `sudo` here. – tripleee Jul 01 '21 at 08:40

1 Answers1

0

If you are root, you can always use su.

if [ -e /home/custom/file.txt ];: then
  su custom -c 'cp -v /home/custom/file.txt /home/custom/backup/file.txt'
  exit 1
fi

If you have sudo, even better; but then remember that your package must depend on it being installed and configured suitably for it to work in your scenario. If your package doesn't already do these things for other reasons, it's probably simpler to just use su. But if you do, simply use sudo -u custom cp ...

For copying a file with a particular ownership, also look at install.

if [ -e /home/custom/file.txt ]; then
  install -o custom -g customgroup -t /home/custom/backup -D \
    /home/custom/file.txt
  exit 1
fi

Notice how the -D option also relieves you of the burden to make sure the target directory exists.

Obviously change customgroup to the correct group name, or omit the -g option.

tripleee
  • 175,061
  • 34
  • 275
  • 318