Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
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
@MichaelMrozek sudo -i is preferred. It requires permissions to run sudo bash. – jordanm Oct 19 '12 at 19:16
up vote 3 down vote accepted

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"
share|improve this answer

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.

share|improve this answer

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)

share|improve this answer
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 posting your answer, you agree to the privacy policy and terms of service.

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