LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Executing command in bash script as a different user? (https://www.linuxquestions.org/questions/programming-9/executing-command-in-bash-script-as-a-different-user-4175498172/)

homer_3 03-14-2014 09:01 AM

Executing command in bash script as a different user?
 
I'm running a bash script as root and want to execute a command in the script as a different user. The lines of interest in the script are below. If I copy and paste the results of the echo to my command line, the script runs as the other user. But If I run the script, the command never executes and no errors are logged to the screen.

Code:

echo "su otheruser -c '$COMMAND'"
$(su otheruser -c '$COMMAND')

I've also tried

Code:

echo "su otheruser -c '$COMMAND'"
su otheruser -c '$COMMAND'


YankeePride13 03-14-2014 09:24 AM

Perhaps put the path to su in your script ? (/bin/su)

homer_3 03-14-2014 09:49 AM

no luck :(

YankeePride13 03-14-2014 09:53 AM

Does it give any errors in the output of the command?

schneidz 03-14-2014 09:58 AM

this is what i get:
Code:

[root@hyper ~]# cat homer.ksh
#!/bin/bash

echo su - schneidz -c 'whoami':
su - schneidz -c 'whoami'

echo su - schneidz -c '$c':
c=whoami
su - schneidz -c '$c'

[root@hyper ~]# ./homer.ksh
su - schneidz -c whoami:
schneidz
su - schneidz -c $c:

i think the single quotes are preventing the value of the variable from being expanded so the script is trying to run it literally (i'm surprised its not returning '$c': command not found to stderr).

homer_3 03-14-2014 09:58 AM

No, I simply see the command I am trying to run echoed to the screen and then my script exits (since it's the last line of the script). When I copy paste the exact command that was echoed, it runs.

Based on schneidz's findings, this works
Code:

#!/bin/bash
X="echo hello"

su otheruser -c "$X"

Thanks.

ntubski 03-14-2014 10:47 AM

Quote:

Originally Posted by schneidz (Post 5134486)
(i'm surprised its not returning '$c': command not found to stderr).

su -c runs the command with a shell, the subshell doesn't get the value of $c, so it expands to an empty string.


All times are GMT -5. The time now is 09:13 PM.