[linux] Use sudo with password as parameter

I would like to run sudo with my password as parameter so that I can use it for a script. I tried

sudo -S mypassword execute_command

but without any success. Any suggestions?

This question is related to linux bash sudo

The answer is


One option is to use the -A flag to sudo. This runs a program to ask for the password. Rather than ask, you could have a script that just spits out the password so the program can continue.


# Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

echo -e "YOURPASSWORD\n" | sudo -S yourcommand

The -S switch makes sudo read the password from STDIN. This means you can do

echo mypassword | sudo -S command

to pass the password to sudo

However, the suggestions by others that do not involve passing the password as part of a command such as checking if the user is root are probably much better ideas for security reasons


You can set the s bit for your script so that it does not need sudo and runs as root (and you do not need to write your root password in the script):

sudo chmod +s myscript

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to sudo

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied How to run SUDO command in WinSCP to transfer files from Windows to linux How to install Intellij IDEA on Ubuntu? pip install: Please check the permissions and owner of that directory How to use sudo inside a docker container? How to fix 'sudo: no tty present and no askpass program specified' error? npm install errors with Error: ENOENT, chmod npm throws error without sudo Is it acceptable and safe to run pip install under sudo? Command not found when using sudo