0

i want to write script inside the script i will do many commands that require to be root like

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install eclipse

but i want to write the password just one time

i tried to write in top

sudo su

to run as root but it stop the script so what i can so to write the password

user234517
  • 175
  • 1
  • 8
  • Will all the commands in the script require root/sudo? – edwin Jan 26 '14 at 00:57
  • It's bad form to have a script request superuser powers (with sudo) during execution if multiple commands will need it. Do all the commands need to be run as superuser? – Thomas Ward Jan 26 '14 at 00:59
  • yes every command in script will need to be root – user234517 Jan 26 '14 at 01:11
  • Usually the shell keep the password valid for 15 minutes, so the you should be required to type it only the first time, or am I missing something? – clobrano Feb 14 '17 at 14:39

2 Answers2

2

The obvious solution: run the script as root

sudo /your/script

Then all commands in the script will be run as root.

If some commands don't need root, just use sudo to change back to a normal user

kiri
  • 28,246
  • 16
  • 81
  • 118
0

If you have commands that don't require sudo, you might check out my answer on this question.

For brevity, though, here is a quick answer:

#!/bin/bash

PW=$1

echo $PW | apt-get update
echo $PW | apt-get upgrade
echo $PW | apt-get install eclipse

Run with bash file_name.bash sudo_pw

The reason for passing it this way is people can't necessarily tell what the parameter you're passing means, so even if someone monitors in some way (even looking over your shoulder), it's still secure.

The primary reason I do this is because most of the commands I run with sudo create objects that need to be manipulated later on, and using sudo command will usually make them inaccessible, even if I sudo next_command. A simplistic example would be creating an Excel file and wanting to manipulate it with another process. Even running with sudo, most of the time, I can't access it again without overwriting it, which then recreates it as an inaccessible object.

Note: This also works as a shell script as there is nothing BASH specific in the syntax, so you could use #!/bin/sh and ./file_name.sh sudo_pw instead, if that is your preference.

csworenx
  • 122