Bash – How to fill the password automatically from .bash_profile when running command as sudo

bashosxpermissionsshell-scriptsudo

I know I could just put something like sudo mypassword in my .bash_profile, but I don't want to run every command as root.

I want password to autofill under following circumstances:

  • only the commands requiring root privileges
  • only commands that I explicitly state I plan to run su to root with sudo

Example:

sudo cd /var/root           #When I type this
Password:                   #I don't want to be prompted for my password
                            #I want to fill it from my `.bash_profile`

But:

cd /var/root                              #When I type this
-bash: cd: /var/root: Permission denied   #I still want this, or the like, returned

I saw this post on increasing sudo timeout, but I don't think it's quite equivalent. For example, I want it to carry across different shell log-in sessions. I could be wrong.

Any suggestions regarding what to (or not to!) add to my .bash_profile, or which method (timeout vs profile) is preferable would be greatly appreciated! Thank you in advance.

Best Answer

If you don't want to be challenged every time for your password then I'd recommend setting it to NOPASSWD in your /etc/sudoers file rather than hardcode your password in your logins. At least this way your primary login's password will remain intact and not be completely exposed in your .bashrc.

To make this change run the command sudo visudo, and change your user accounts entry to something like this:

userX        ALL=(ALL)       NOPASSWD: ALL
Related Question