Search code examples
linuxbashshellsudo

Why can't I use 'sudo su' within a shell script? How to make a shell script run with sudo automatically


I cannot figure out what's wrong with this. When I run it in terminal and enter password, nothing happens, but if I run every command separately in terminal, it works. Thank you!

#!/bin/bash    

sudo su;
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

Solution

  • Command sudo su starts an interactive root shell, but it will not convert the current shell into a root one.

    The idiom to do what you want is something along the lines of this (thanks to @CharlesDuffy for the extra carefulness):

    #check for root
    UID=$(id -u)
    if [ x$UID != x0 ] 
    then
        #Beware of how you compose the command
        printf -v cmd_str '%q ' "$0" "$@"
        exec sudo su -c "$cmd_str"
    fi
    
    #I am root
    mkdir /opt/D3GO/
    #and the rest of your commands
    

    The idea is to check whether the current user is root, and if not, re-run the same command with su