iLemming
iLemming

Reputation: 36166

Applying sudo to some commands in script

I have a bash script that partially needs to be running with default user rights, but there are some parts that involve using sudo (like copying stuff into system folders) I could just run the script with sudo ./script.sh, but that messes up all file access rights, if it involves creating or modifying files in the script.

So, how can I run script using sudo for some commands? Is it possible to ask for sudo password in the beginning (when the script just starts) but still run some lines of the script as a current user?

Upvotes: 0

Views: 889

Answers (2)

Marc Liyanage
Marc Liyanage

Reputation: 4681

You could add this to the top of your script:

while ! echo "$PW" | sudo -S -v > /dev/null 2>&1; do
    read -s -p "password: " PW
    echo
done

That ensures the sudo credentials are cached for 5 minutes. Then you could run the commands that need sudo, and just those, with sudo in front.

Edit: Incorporating mklement0's suggestion from the comments, you can shorten this to:

sudo -v || exit

The original version, which I adapted from a Python snippet I have, might be useful if you want more control over the prompt or the retry logic/limit, but this shorter one is probably what works well for most cases.

Upvotes: 4

Greg Hewgill
Greg Hewgill

Reputation: 992975

Each line of your script is a command line. So, for the lines you want, you can simply put sudo in front of those lines of your script. For example:

#!/bin/sh

ls *.h
sudo cp *.h /usr/include/
echo "done" >>log

Obviously I'm just making stuff up. But, this shows that you can use sudo selectively as part of your script.

Just like using sudo interactively, you will be prompted for your user password if you haven't done so recently.

Upvotes: 1

Related Questions