Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i run a sudo command in Bash script?

Tags:

bash

shell

I want to run the following sample bash script which needs sudo password for a command

#!/bin/bash
kinit #needs sudo password
vi hello.txt  

while running the above script it is asking for password.
How can i pass the username and password in the command itself or is there any better way i can skip passing my password in the script ?

like image 542
Shivam Agrawal Avatar asked Aug 21 '13 18:08

Shivam Agrawal


1 Answers

TL;DR

You can't—at least, not the way you think.

Longer Answer with Alternatives

You have a couple of options:

  1. Authenticate interactively with sudo before running your script, e.g. sudo -v. The credentials will be temporarily cached, giving you time to run your script.
  2. Add a specific command such as /usr/lib/klibc/bin/kinit to your sudoers file with the NOPASSWD option. See sudoers(5) and and visudo(8) for syntax.
  3. Use gksudo(1) or kdesu(1) with the appropriate keyring to cache your credentials if you're using a desktop environment.

One or more of these will definitely get you where you want to go—just not the way you wanted to get there.

like image 152
Todd A. Jacobs Avatar answered Sep 30 '22 12:09

Todd A. Jacobs