How can we write a shell script to become root? That is I donot want to input the password at prompt it should be within the script itself. I was trying to make but failed to do so.Is it possible, if Yes please Explain.

  • Does it need to be a shell script? I don't see how that would be possible, but you could set it up so sudo su or sudo bash works without a password – Michael Mrozek Oct 19 '12 at 17:36
  • 1
    @MichaelMrozek sudo -i is preferred. It requires permissions to run sudo bash. – jordanm Oct 19 '12 at 19:16

You can write a script using expect tool.

In Redhat, expect package comes by default. But in Ubuntu you need to install it separately.

You can check this by using commands:

$ rpm -qa | grep expect for Redhat

$ dpkg -l expect for Ubuntu

The following script will do your work:


spawn su -
expect "Password: "
send "password\r"

Storing the cleartext of the root password in a file is inherently dangerous - there are lots of routes by which it can be recovered.

This appears to be an XY problem.

The unixy way of delegating permissions is via the setuid bit - but this can only be applied to binary executables, not shell scripts. As jordanm states, applying setuid to the shell itself is very dangerous - that's why sudo exists - it has a setuid bit and validates user requests against the sudoers file to give a fine-grained control over access. But sudo also has some gotchas.


The simplest way is to make a suid copy of the shell:

cp /bin/bash $HOME/bin/becomeroot
sudo chown root $HOME/bin/becomeroot
sudo chmod 4750 $HOME/bin/becomeroot
hash -r

Then, running becomeroot will start a bash subshell running as root.

However, I would be remiss if I didn't give you this advice: don't do that. It's unwise to make it so easy for malware to escalate its privileges to root. Instead, just install sudo and learn to use it whenever you need to run something as root.


You can set the SUID sticky bit:

chmod 2664 your-file

That will cause the software to run as the owner of the file. So of course, you'll have to change ownership to root:

sudo chown root your-file

(assuming you are found in the sudoers file, and you've installed sudo)

  • 1
    setuid does not work on shell scripts unless you setuid the shell binary (not recommended). – jordanm Oct 19 '12 at 19:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.