w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Create files in my shell script owned by root without the need for sudo

You can do what you want using fakeroot. It's a library that makes programs think they're running as root, when they are not. IIRC, it is used by dpkg to allow non-root users to build .deb packages that contain root-owned files.

Check out this shell script:

#!/bin/bash

mkdir image
touch image/user-owned
touch image/root-owned

chown renato.renato image/user-owned
chown root.root     image/root-owned

tar cf image.tar image

Normally, I would only be able to create this tar archive as root. However, if I use fakeroot:

$ fakeroot ./create-image.sh
$ tar tvf image.tar

drwxr-xr-x root/root         0 2014-04-09 01:09 image/
-rw-r--r-- root/root         0 2014-04-09 01:09 image/root-owned
-rw-r--r-- renato/renato     0 2014-04-09 01:09 image/user-owned

However, the files on the disk are still user-owned, so no security risk here:

$ ls -l image/

total 0
-rw-r--r-- 1 renato renato 0 Abr  9 01:09 root-owned
-rw-r--r-- 1 renato renato 0 Abr  9 01:09 user-owned




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.