Dusan Milosevic
Dusan Milosevic

Reputation: 60

In this script, ~ is /root/. How to be in /home/name-of-the-user/?

#!/bin/bash    

#become root
UID=$(id -u)
if [ x$UID != x0 ] 
then
    printf -v cmd_str '%q ' "$0" "$@"
    exec sudo su -c "$cmd_str"
fi


mkdir ~/.D3GO/; 
cp -a `pwd`/viewright_backup/. ~/.D3GO/;

mkdir /opt/D3GO/;
cp `pwd`/D3GO /opt/D3GO/;
cp `pwd`/D3GO.png /opt/D3GO/;
cp `pwd`/D3GO.desktop /usr/share/applications/;
chmod +x /opt/D3GO/D3GO;

As you can see, because this uses ~, and the script is ran as root, it creats the folder.D3GO in the /root/ directory. Is it possible to create it in the home directory. For example, if the script is located in /home/user/Downloads/, it should create the directory in home/user/. If it's located in /home/user2/Downloads/dir/, it should create it in /home/user2/ etc. Is this possible? Thanks!

Maybe something like:

#!/bin/bash    

#remember the username
user = $(whoami);

#become root
UID=$(id -u)
if [ x$UID != x0 ] 
then
    printf -v cmd_str '%q ' "$0" "$@"
    exec sudo su -c "$cmd_str"
fi


mkdir /home/`$user`/.D3GO/; 
cp -a `pwd`/viewright_backup/. /home/`$user`/.D3GO/;

Upvotes: 0

Views: 258

Answers (2)

Bill Karwin
Bill Karwin

Reputation: 562378

To answer your question literally:

sudo -E preserves environment variables (although some variables may be overwritten by the new shell).

export MY_HOME=$HOME
. . .

exec sudo -E su -c "$cmd_str"

Then you can reference $MY_HOME in the script and it should be set to the original user's $HOME.

But I agree with the comment from @CharlesDuffy, you should sudo for individual commands you need to run. If you do that, then arguments to the sudo command are substituted from the original shell.

For example:

sudo cp -a `pwd`/viewright_backup/. $HOME/.D3GO/;

This uses the non-root user's $HOME, because the variable substitution happens before the sudo command is executed.

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295472

if [ "$UID" != 0 ] 
then
    printf -v set_home_prefix 'HOME=%q; ' "$HOME"
    printf -v cmd_str '%q ' "$0" "$@"
    exec sudo su -c "$set_home_prefix $cmd_str"
fi

I took the liberty of correcting the invalid quoting you were given in the answer you accepted on the other question.

Upvotes: 1

Related Questions