eli
eli

Reputation: 29

Retain root privileges during long processes

I have a bash script that makes a backup of my data files (~50GB). The script is basically something like this:

sudo tar /backup/mydata1 into old-backup-1.tar
sudo tar /backup/mydata2 into old-backup-2.tar
sudo rsync /mydata1 to /backup/mydata1
sudo rsync /mydata2 to /backup/mydata2

(I use sudo because some of the files are owned by root).

The problem is that after every command (because it takes a long time) I loose root privileges and if I'm not present at the computer then the su prompt gets timed out and the script ends in the middle of the job.

Is there a way to retain su privileges during the entire script? What is the best way to approach this situation? I prefer to run the script under my user.

Upvotes: 0

Views: 122

Answers (2)

Cyrus
Cyrus

Reputation: 88636

With a second shell:

sudo bash -c "command1; command2; command3; command4"

Upvotes: 1

Petr Skocik
Petr Skocik

Reputation: 60068

Perhaps like this:

#!/bin/bash -eu

exec sudo /bin/bash <<'EOF'
    echo I am $UID
    whoami
    #^the script
EOF

Alternatively, you could put something like:

if ! [ $(id -u)  -eq 0 ]; then
    exec sudo "$0" "$@"
fi

at the top.

Upvotes: 0

Related Questions