I've been curious ever since I've started bash scripting in Ubuntu, and I have been wondering if there was a way to log in as root or run a sudo command without physically typing the password manually when it prompts you in the terminal.

Is it possible to hard-code the password into a line, such as "echo mypassword" and have sudo read through the echo command instead of typing for myself?

I've looked around that you could, if you had set the root to have no password, which is something I do not want.

I've just been playing around with bash and seeing if I could login as root and run a command in root through the bash script only:


echo mypassword | sudo apt-get install frozen-bubble

This is just out of my pure curiosity, and was just wondering how to implement it if it was possible. Thanks.

IF this is relevant, I'm using Ubuntu 9.04.

4 Answers 4


You should not hardcode your password. If you want use sudo without password, you must edit sudoers file. To edit sudoers, type command

$ sudo visudo

Visudo uses vi as editor. If you are not familiar in vi, you could set environment variable VISUAL or EDITOR to you favourite editor, eg.VISUAL=nano. The following environment variables are used only if visudo was configured with the --with-env-editor

In sudoers file, you should place line

your_username ALL=(ALL) NOPASSWD: ALL


%some_groupname ALL=(ALL) NOPASSWD: ALL

or (be careful, this enable sudo without password for all users)


For more information use man sudoers

  • +1 sudo is the secure way forward
    – Coops
    Oct 28, 2009 at 17:14

You can't and shouldn't hardcode the password in the script. The right way to do this is to make sure that the user running the script is in the sudoers file, and then use sudo in the script.


Hardcoding passwords is bad. Use sudo with no password.


One other interesting thought here.....use ssh with generated public/private keys. The key can be configured to allow only certain commands to be execute with it.

If you use sudo with no password required, I'd probably make sure that the command set is limited and not ALL.

Your Answer

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