Home > Mobile >  How to run different functions with different users inside bash script
How to run different functions with different users inside bash script

Time:05-05

I have a script structured in functions which is executed using the root user. Nevertheless, it is needed to execute the most part of the script as another user. My question here is how to execute different functions using different users depending on the function that'll be executed.

Example

#!/bin/bash

function A() {        # Run as a non-root user
  ...
}

function B() {        # Run as a non-root user
  ...
}


function C() {        # Run as a non-root user
  ...
}

function D() {        # Run as a root user
  ...
}

function main() {
  A
  B
  C
  D
}

main

As said before, the script is called using the root user:

root@host:~# script.sh

The main goal here is to know if this is possible and how to do it, without changing the way the script is called (i.e. the script being called via another user but root)

CodePudding user response:

You could do this with the help of the runuser command.

To use your template, this looks like this :

#!/bin/bash

function user(){
runuser -l user -c "whoami"
}

function main(){
 user
}
main

CodePudding user response:

#work user as example
su - work -c "pwd" 

like this?

  • Related