Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to run a command as a different user, but within a detached screen and can't seem to get the syntax quite right. If I split the commands I can get them to work, but when I piece them all together, nothing happens.

What I am trying:

COMMAND='COUNTER=0; while [ $COUNTER -lt 10 ]; do echo Count: $COUNTER; let COUNTER=COUNTER+1; sleep 15; done'

if [ $USER_CURRENT = $USER_RUN_AS ]; then
    screen -dmS $REMOTE_REPO_NAME -c "$COMMAND 2>&1 >> $LOG_FILE_URI"        

     # This works, but I would like it to run in detached screen
     # sudo su -s /bin/bash $USER_RUN_AS -c " $COMMAND 2>&1 >> $LOG_FILE_URI "

     # Tried piping screen to the sudo command
     # screen -dmS $REMOTE_REPO_NAME $COMMAND | sudo -S su -s /bin/bash $USER_RUN_AS 2>&1 >> $LOG_FILE_URI

     # Tried passing the command to screen
     screen -dmS $REMOTE_REPO_NAME -c "$COMMAND 2>&1 >> $LOG_FILE_URI | sudo -S su -s /bin/bash $USER_RUN_AS"

share|improve this question
up vote 1 down vote accepted

I think your second and third attempts have all the right pieces, but out of order.  Try

sudo su -s /bin/bash $USER_RUN_AS -c "screen -dmS $REMOTE_REPO_NAME \"$COMMAND 2>&1 >> $LOG_FILE_URI\" "

I don’t think it makes sense to be using a pipe.

share|improve this answer
I'm trying to run the command as another user within a screen. – Mike Purcell Jul 22 '13 at 4:30
@MikePurcell: Oops; my bad. I’ve made another try. – Scott Jul 22 '13 at 17:09
This appears to work for me, but I'm not good enough with *nix to say with 100% certainty that it's always right. +1 anyways, sir. – Patrick M Jan 9 '14 at 16:35
screen -dmS $REMOTE_REPO_NAME sudo su - $USER_RUN_AS -c "$COMMAND 2>&1 >> $LOG_FILE_URI"

is all you need. Just run sudo within your screen. -c switch to screen is "read config file". This is probably not what you want.

  -c file
        override  the default configuration file from "$HOME/.screenrc" to
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .