Home > Mobile >  How can I request elevated permissions in a bash script's begin and let it go at the end?
How can I request elevated permissions in a bash script's begin and let it go at the end?

Time:03-26

I have a script (myscript.sh) which runs a few commands which need elevated privileges (i.e. needs to run with sudo).

Script is quite complex, but to demonstrate it is like below:

#!/bin/bash
echo "hello"
command1_which_needs_sudo
echo "hello2"
command2_which_needs_sudo
echo "hello3"
...

If I run it as a normal user without the required privileges:

$ ./myscript.sh
hello
must be super-user to perform this action

However if I run it with the correct privileges, it will work fine:

$ sudo ./myscript.sh
hello
hello2
hello3

Can I somehow achieve to run myscript.sh without sudo, and make the script requesting the elevated privileges only once in the beginning (and pass it back once it has finished)?

So obviously, sudo command1_which_needs_sudo will not be good, as command2 also need privileges.

How can I do this if I don't want to create another file, and due to script complexity I also don't want to do this with heredoc syntax?

CodePudding user response:

If your main concern is code clarity, using wrapper functions can do a lot of good.

# call any named bash function under sudo with arbitrary arguments
run_escalated_function() {
  local function_name args_q
  function_name=$1; shift || return
  printf -v args_q '%q ' "$@"
  sudo bash -c "$(declare -f "$function_name"); $function_name $args_q"
}

privileged_bits() {
  command1_which_needs_sudo
  echo "hello2"
  command2_which_needs_sudo
}

echo "hello"
run_escalated_function privileged_bits
echo "hello3"

CodePudding user response:

With a subshell:

echo "hello"

sudo bash -c "{
  command1_which_needs_sudo
  echo "hello2"
  command2_which_needs_sudo
}"

echo "hello3"

CodePudding user response:

Here's solution taken from Run sudo -s inside shell script

#!/bin/bash

if [[ $EUID -ne 0 ]]
then
    exec sudo "$0" "$@"
fi

echo "hello"
command1_which_needs_sudo
echo "hello2"
command2_which_needs_sudo
echo "hello3"
# ...
  • Related