Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 268
Dusan Milosevic Avatar asked Jul 08 '14 19:07

Dusan Milosevic


People also ask

Can I run sudo in a script?

In Linux, the sudo command allows us to execute a command or script as the superuser. However, by default, the sudo command works in an interactive mode.


1 Answers

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

like image 89
rodrigo Avatar answered Sep 23 '22 08:09

rodrigo