Quantcast
Viewing all articles
Browse latest Browse all 4

Answer by LeonidMew for How to elevate privileges to root in bash and return back?

To elevate privileges for few commands in script use sudo with heredoc syntax:

possiblevariable=something    
sudo /bin/bash <<EOF
    cd /somedir
    pwd
    commandasroot1 "$possiblevariable"
    commandasroot2
EOF
nonrootcommand (and not in /somedir)

Testing cd: (working dir changed inside heredoc, but restores as it be before at end of heredoc)

leonid@DevSSD:~$ sudo bash <<EOF
> cd /tmp
> pwd
> EOF
[sudo] password for leonid: 
/tmp
leonid@DevSSD:~$ 

One more example, shows how variables substitution work in heredoc:

leonid@DevSSD:~$ sudo bash <<EOF
    cd /tmp
    echo $PWD; echo \$PWD
EOF
[sudo] password for leonid: 
/home/leonid
/tmp
leonid@DevSSD:~$ 

Update: example how you can get output into variable

leonid@DevSSD:~$ variable=$(sudo bash <<EOF
    cd /tmp
    echo $PWD; echo \$PWD
EOF
)
[sudo] password for leonid: 
leonid@DevSSD:~$ echo $variable
/home/leonid /tmp

Viewing all articles
Browse latest Browse all 4

Trending Articles