Prompt for sudo password from bash

14.Apr.2014

Lets say that we’re writing bash script that should perform all the commands as a regular user, but it should also edit some files for which sudo command is needed.

Writing sudo command won’t be much of a help as script might not ask for the password, and instead might just respond with “Permission denied”.

In our example, we would like to programatically append new line to /etc/hosts. To do this, we would need sudo command, and thanks to this Lauri Ranta, we found an easy way to do it.

Assuming that we have previously gathered data about IP and DOMAIN from shell, this is how we would append new line to hosts file and let script to ask for password.

1
2
3
4
5
6
#!/bin/bash
 
IP="192.168.33.11"
DOMAIN="stuntgento.local"
 
sudo bash -c "echo '$IP $DOMAIN' >> /etc/hosts"

We hope you’ll find this solution helpful.

Happy coding!