Insert a Password into the Terminal Through a Script?

I was wondering if there was a way to insert a password when it's asked for in the terminal while using a script. I would prefer to not have to type it but I suppose that's not the worst thing that could happen.

2

1 Answer

You can use something like this in your script:

echo 'yourPassword' | sudo -S yourCommand

The -S flag makes sudo read the password from the standard input. You can check it in manual pages using man sudo:

-S, --stdin

Write the prompt to the standard error and read the password from the standard input instead of using the terminal device. The password must be followed by a newline character.

If you get an error using this, it's because your sudo access token is active, to get around that, you could use -k to reset the access token:

echo 'yourPassword' | sudo -kS yourCommand

Hope it helps.

Your Answer

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

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest