Running command with another user within a shell script

Asked

Viewed 18,812 times

6

I have a shell script that I need to run some commands with a linux user, and some other commands with another user.

Something more or less like this:


#!/bin/bash

  echo 'rodando com usuário A'
  comando1
  comando2
  comando3

  echo 'Rodando com Usuário B'
  sudo su comando4

The problem is that I would like to perform all commands in the same script. But once the command with the second user is started, a new session bash is initiated. It is possible to execute commands with 2 different users in the same script?

3 answers

4

You can use the su as follows to do this in the shell script:

su -c "comando" -s /bin/sh nomedoUsuario

Where the parameter -c specifies to pass a single command to the shell and -s is used to specify with which shell call the command.

Another way to do this is by using the sudo as follows:

sudo -H -u nomedoUsuario bash -c "comando" 

The parameter -h is a security policy that allows defining the environment variable $HOME for the specified user(root is by default). -u specifies the user to execute the command.

  #!/bin/bash

  echo 'rodando com usuário A'
  sudo -H -u nomedoUsuario bash -c "Foo" 
  sudo -H -u nomedoUsuario bash -c "Bar" 

  echo 'Rodando com Usuário B'
  sudo -H -u nomedoUsuario bash -c "Baz" 

1

I use the command runuser. Basic syntax: runuser -l usuario -c comando.

The commands below serve as a test, showing which current user and bash PID:

whoami && echo $$
sleep 2
runuser -l usuario1 -c "whoami && echo $$"
sleep 2
runuser -l usuario2 -c "whoami && echo $$"

For more information run the command man runuser.

  • Well appreciated your help, I will also test your suggestion. Thank you.

-2

I was able to solve with this command:

su otrs /opt/otrs/bin/otrs.Daemon.pl start -s /usr/bin/perl

Browser other questions tagged

You are not signed in. Login or sign up in order to post.