MarksCode MarksCode - 3 months ago 16
Bash Question

Run sudo -s inside shell script

I'm trying to make a shell script that installs and configures a log centralizing program called logentries. They have instructions on their website to copy and paste some lines into your command line which completes this process. I tried copying and pasting these exact bash commands into a shell script so I can just run the one script instead of copying and pasting all their instructions.

Here's the contents of my script:

sudo -s
echo "sudod"
tee /etc/yum.repos.d/logentries.repo <<EOF
[logentries]
name=Logentries repo
enabled=1
metadata_expire=1d
baseurl=http://rep.logentries.com/amazonlatest/\$basearch
gpgkey=http://rep.logentries.com/RPM-GPG-KEY-logentries
EOF
yum update
yum install logentries


I inserted the echo statement on line 2 to test if the script was even getting to that point, but when I run the script that doesn't even get outputted. I guess that means I can't just use
sudo -s
inside a script like I can on the command line.

Does anyone know how I can make these command line instructions execute in a shell script?

Answer

Every command in a shell script, is run independently. The script is parent process which invokes commands as child processes. Thus, sudo -s creates a new process that opens root shell. However, this process cannot execute the commands later.

You can also see your echo output being printed, if you do exit from root shell. This happens because, when you exit, the process of root shell gets terminated.

You can write all the commands, except sudo -s in shell script. Make it executable by chmod +x install_logentries.sh. And execute it via sudo install_logentries.sh

Another alternative is to embed commands as a child process using << (as given below):

#!/bin/bash
sudo -s << SCRIPT
tee /etc/yum.repos.d/logentries.repo <<EOF

[logentries]
name=Logentries repo
enabled=1
metadata_expire=1d
baseurl=http://rep.logentries.com/amazonlatest/\$basearch
gpgkey=http://rep.logentries.com/RPM-GPG-KEY-logentries

EOF
yum update
yum install logentries
SCRIPT
Comments