How to run a function from script as another user

1k views Asked by At

In a bash script, I am trying to run a function which pass as parameter a command line. And so I am trying to pass a find command as another user.

Instead of running straight the find command, I have a function run-command which basically run and output the command and the result. Nothing complex.

I am trying to run this command:
su - ${USER} -c '$(run-command find ${DIR} -name TEST* -exec rm -rf "{}" +)'
But it is failing, message error:

I am able to run find command as another user as following:
- su - ${USER} -c '$(find ${DIR} -name TEST* -exec rm -rf "{}" +)'
- sudo -u ${USER} find ${DIR} -name "TEST*" -exec rm -rf "{}" +

It looks like I can not call a function of the script when I switch with su command to another user.

  • I want to continue my script as the current user after running this command line.
  • I do not want to give special privilege to current user to run that command himself (nothing to modify in /etc/sudoers).

Thanks in advance for your help.

1

There are 1 answers

0
Aidan Lovelace On
su - ${USER} -c '$(run-command find ${DIR} -name TEST* -exec rm -rf "{}" +)'

The first issue you're having is that this command is running run-command... as the already logged in user and then passing the result to su.... To mend this, simply change it to the following:

su - ${USER} -c 'run-command find ${DIR} -name TEST* -exec rm -rf "{}" +'

The next issue here is that su is creating a new shell session, so we cannot pass our current variables and functions to the new session. I propose that you create a shell script that contains run-command and running that from su -c..., bringing our final command to:

su - ${USER} -c '/path/to/run-command.sh find ${DIR} -name TEST* -exec rm -rf "{}" +'

or

su - ${USER} -c 'bash /path/to/run-command.sh find ${DIR} -name TEST* -exec rm -rf "{}" +'