Execute a shell script in current shell with sudo permission

sudo in shell script without password prompt
how to automate sudo command in shell script
execute unix command in shell script
shell script get sudo
sudo shell script command not found
shell script run command as root
bash script execute command as sudo
sudo with password in script

For executing 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 shell?

Thanks in advance..

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.)

How do I run a 'sudo' command inside a script?, How do I run a sudo command in a shell script? First you can cat the file into a variable with sudo permissions. Then you can evaluate the variable to execute the code in the file in your current shell. Here is an example of reading and executing an .env file (ex Docker) sensitive_stuff=$(sudo cat ".env") eval "$ {sensitive_stuff}" echo $ADMIN_PASSWORD. share.

I'm not sure if this breaks any rules but

sudo bash script.sh

seems to work for me.

The Right Way to Use sudo in Scripts, 3 Answers. chmod u+x program_name . Then execute it. If that does not work, copy the program from the USB device to a native volume on the system. gsudo is a sudo equivalent for Windows, with a similar user-experience as the original *nix sudo. It allows to run commands with elevated permissions, or to elevate the current shell, in the current console window or a new one. gsudo is very easy to install and use, and has more features. Its

I think you are confused about the difference between sourcing and executing a script.

Executing a script means creating a new process, and running the program. The program can be a shell script, or any other type of program. As it is a sub process, any environmental variables changed in the program will not affect the shell.

Sourcing a script can only be used with a bash script (if you are running bash). It effectively types the commands in as if you did them. This is useful as it lets a script change environmental variables in the shell.


Running a script is simple, you just type in the path to the script. . is the current directory. So ./script.sh will execute the file script.sh in the current directory. If the command is a single file (eg script.sh), it will check all the folders in the PATH variable to find the script. Note that the current directory isn't in PATH, so you can't execute a file script.sh in the current directory by running script.sh, you need to run ./script.sh (unless the current directory is in the PATH, eg you can run ls while in the /bin dir).

Sourcing a script doesn't use the PATH, and just searches for the path. Note that source isn't a program - otherwise it wouldn't be able to change environmental variables in the current shell. It is actually a bash built in command. Search /bin and /usr/bin - you won't find a source program there. So to source a file script.sh in the current directory, you just use source script.sh.


How does sudo interact with this? Well sudo takes a program, and executes it as root. Eg sudo ./script.sh executes script.sh in a sub process but running as root.

What does sudo source ./script.sh do however? Remember source isn't a program (rather a shell builtin)? Sudo expects a program name though, so it searches for a program named source. It doesn't find one, and so fails. It isn't possible to source a file running as root, without creating a new subprocess, as you cannot change the runner of a program (in this case, bash) after it has started.

I'm not sure what you actually wanted, but hopefully this will clear it up for you.


Here is a concrete example. Make the file script.sh in your current directory with the contents:

#!/bin/bash    
export NEW_VAR="hello"
whoami
echo "Some text"

Make it executable with chmod +x script.sh.

Now observe what happens with bash:

> ./script.sh
david
Some text
> echo $NEW_VAR

> sudo ./script.sh
root
Some text
> echo $NEW_VAR

> source script.sh
david
Some text
> echo $NEW_VAR
hello
> sudo source script.sh
sudo: source: command not found

Ubuntu says "bash: ./program Permission denied", Therefore, to run a shell script or program as root, you need to use sudo command. (finds process listening on a port) with root privileges. This way, we risk exposing our systems to various attacks, because an attacker who manages to gain access to an unsecure (without superuser privileges) directory that has been added to secure_path, can run a malicious script/program with sudo command.

Basically sudo expects, an executable (command) to follow & you are providing with a .

Hence the error.

Try this way $ sudo setup.sh


How to Run Shell Scripts with Sudo Command in Linux, Instead, remove the sudo from the script and run the script itself with sudo : That way, all commands within the script will be run with root privileges and you #!/bin/bash # this declares that current user is a sudoer sudo tee  typing 'sudo' before a command will execute the program using root privileges. Be careful when doing this, bad things can happen if you're not sure what you're doing. Obviously you can omit the /path/to if you saved this script directly in your home directory.

If you really want to "ExecuteCall a shell script in current shell with sudo permission" you can use exec to...

replace the shell with a given program (executing it, not as new process)

I insist on replacing "execute" with "call" because the former has a meaning that includes creating a new process and ID, where the latter is ambiguous and leaves room for creativity, of which I am full.

Consider this test case and look closely at pid 1337

# Don't worry, the content of this script is cat'ed below
$ ./test.sh -o foo -p bar

User ubuntu is running...
 PID TT       USER     COMMAND
 775 pts/1    ubuntu   -bash
1408 pts/1    ubuntu    \_ bash ./test.sh -o foo -p bar
1411 pts/1    ubuntu        \_ ps -t /dev/pts/1 -fo pid,tty,user,args

User root is running...
 PID TT       USER     COMMAND
 775 pts/1    ubuntu   -bash
1337 pts/1    root      \_ sudo ./test.sh -o foo -p bar
1412 pts/1    root          \_ bash ./test.sh -o foo -p bar
1415 pts/1    root              \_ ps -t /dev/pts/1 -fo pid,tty,user,args

Take 'exec' out of the command and this script would get cat-ed twice. (Try it.)

#!/usr/bin/env bash

echo; echo "User $(whoami) is running..."
ps -t $(tty) -fo pid,tty,user,args

if [[ $EUID > 0 ]]; then
    # exec replaces the current process effectively ending execution so no exit is needed.
    exec sudo "$0" "$@"
fi

echo; echo "Take 'exec' out of the command and this script would get cat-ed twice. (Try it.)"; echo
cat $0

Here is another test using sudo -s

$ ps -fo pid,tty,user,args; ./test2.sh
  PID TT       USER     COMMAND
10775 pts/1    ubuntu   -bash
11496 pts/1    ubuntu    \_ ps -fo pid,tty,user,args

User ubuntu is running...
  PID TT       USER     COMMAND
10775 pts/1    ubuntu   -bash
11497 pts/1    ubuntu    \_ bash ./test2.sh
11500 pts/1    ubuntu        \_ ps -fo pid,tty,user,args

User root is running...
  PID TT       USER     COMMAND
11497 pts/1    root     sudo -s
11501 pts/1    root      \_ /bin/bash
11503 pts/1    root          \_ ps -fo pid,tty,user,args

$ cat test2.src
echo; echo "User $(whoami) is running..."
ps -fo pid,tty,user,args

$ cat test2.sh
#!/usr/bin/env bash

source test2.src

exec sudo -s < test2.src

And a simpler test using sudo -s

$ ./exec.sh
bash's PID:25194    user ID:7809
systemd(1)───bash(23064)───bash(25194)───pstree(25196)

Finally...
bash's PID:25199    user ID:0
systemd(1)───bash(23064)───sudo(25194)───bash(25199)───pstree(25201)

$ cat exec.sh
#!/usr/bin/env bash

pid=$$
id=$(id -u)
echo "bash's PID:$pid    user ID:$id"
pstree -ps $pid

# the quoted EOF is important to prevent shell expansion of the $...
exec sudo -s <<EOF
echo
echo "Finally..."
echo "bash's PID:\$\$    user ID:\$(id -u)"
pstree -ps $pid
EOF

If I sudo execute a Bash script file, will all commands inside the Bash , Q#1: Will I only be prompted for a sudo password once, or will I need to enter the sudo password on each invocation of a command inside the script, that needs  While it is possible to run scripts, such as shell scripts, without having execute permissions, the script will not be able to execute any commands in which the user does not have execute permissions. We can run a script by using it as an argument to the shell, but in order to do this, we must have at least read permissions. Many scripts have read permissions for all users, but execute permissions only for one user, or for a group of users.

How to run .sh file shell script (bash/ksh) in Linux / UNIX, The procedure to run the .sh file shell script on Linux is as follows: without root, you won't have the necessary permissions to install The install.sh is in the current directory so you run it as above or as follows too: bash  Buy Shell Scripts at Amazon. Free Shipping on Qualified Orders.

Unix Basics, In bash shell, the current working directory is also shown in the command and execute permissions, // others (the world) have no permission -rwx------ root root 

source, By using source , we can easily create configuration files for our shell scripts as well. which shell executes it, and second, the file does not need executable permissions. alias reload='source ~/.mynetworkrc.sh' # Get a root shell alias root='sudo -i' As source executes its commands in the current shell environment, this 

Comments
  • Despite the excellent answers, I think the problem is almost just a typo. Delete the first period that is by itself.
  • @beroe you are in error. The problem is not a typo. If setup.sh does not have execute privileges, then you must explicitly interpret it with bash. This can be done as bash setup.sh or source setup.sh or . setup.sh. However, because the latter 2 are bash built-ins, only the 1st form can be used with sudo which requires an executable. You can use sudo which bash and sudo which source and sudo which . to see what sudo will find.
  • @BrunoBronosky it looked (looks) to me like they are trying to run the first lone dot as a command. Since this specifies the current working directory, which is not a command, it throws that error. If they put ./setup.sh it would be a different story.
  • @beroe A lone dot is a shell command -- specifically, it's a shell builtin that's equivalent to the source command (also a builtin).
  • I'm not sure why this is the accepted answer when @JaseC's answer below seems to work for me. sudo bash myscript.sh does exactly what I was looking for, and what the OP seemed to be asking for.
  • @dalesikkema: sudo bash myscript.sh will run the script in a subshell, rather than the current shell. If that works in your situation, great -- but this particular question is about running the script as root in the current shell.
  • The entire premise of ambiguous because of the inaccurate word choice. "For executing a shell script in current shell, we need to use a period" No, that period doesn't execute, it sources, inserts, reads, or interprets. Execution implies a disparate PID. So, we are unclear if/why they might care about the PID of their current shell.
  • I think because you're instantiating a shell with root privileges and running the script within it.
  • This is the exact answer to the question
  • This is not the "exact" answer to the question. It doesn't execute the script in the current shell.
  • but sudo sh setup.sh creates a new shell to execute the script. I want to execute in same shell.
  • But that requires setup.sh to be in PATH.
  • I got a down vote today with no comment. How is that helpful to anyone? Enjoy losing your 2 reputation points. (That's right. It takes your reputation down 2 points in order to give me 1 down vote.)
  • I thought your answer was pretty extensive, here have an up vote!