0

I have a script that calls several other script and I run the script as sudo sudo ./main_script.sh

main_script.sh

#! /bin/bash
set -e

. /scritp1.sh
. /scritp2.sh
. /scritp3.sh
. /scritp4.sh

Is there any way to prevent one of the subscripts from running as sudo? (ie. scripts 1 2 and 4 run as sudo and script 3 run as normal)

2
  • 1
    Do the subscripts need to be run with . (or source), or can they be run in subprocesses, like normal scripts? Commented Aug 21, 2021 at 19:22
  • hi @GordonDavisson the subscripts are standalone scripts that are also sometimes run by themselves with .. Commented Aug 21, 2021 at 19:53

1 Answer 1

1

This should achieve what you expected :

#! /bin/bash
set -e

. /scritp1.sh
. /scritp2.sh
sudo -u $SUDO_USER bash /scritp3.sh
. /scritp4.sh
Sign up to request clarification or add additional context in comments.

6 Comments

is that the right way round? So script3 will NOT run as sudo ?
script3 will run as the original user which is $SUDO_USER.
It's probably best to check whether $SUDO_USER is set first (in case the main script was run some other way, like when directly logged in as root). Something like if [ -z "$SUDO_USER" ]; then echo "Not running via sudo" >&2 ... Also, note that this will run scritp3.sh in a subprocess (as it must, to change users), not in the main shell process like . would.
@GordonDavisson Testing $SUDO_USER is set is a good point, which OP should do in the first place. As all scripts are standalone, OP should not use . or source.
@Philippe can you explain why I should not use . please.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.