Search code examples
linuxbashshellpermissionssudo

Execute a shell script in current shell with sudo permission


To execute a shell script in current shell, we need to use a period . or a source command. But why does it not work with a sudo permission?

I have a script with execute permission called setup.sh. When I use a period, I get this:

$ sudo . ./setup.sh 
sudo: .: command not found

The source command also produces a similar error. Am I missing out something? What should I do to run the script with sudo permission in the same/current shell?


Solution

  • What you are trying to do is impossible; your current shell is running under your regular user ID (i.e. without root the access sudo would give you), and there is no way to grant it root access. What sudo does is create a new *sub*process that runs as root. The subprocess could be just a regular program (e.g. sudo cp ... runs the cp program in a root process) or it could be a root subshell, but it cannot be the current shell.

    (It's actually even more impossible than that, because the sudo command itself is executed as a subprocess of the current shell -- meaning that in a sense it's already too late for it to do anything in the "current shell", because that's not where it executes.)