(some code)
chown USER1 filename

su - USER1 -c "
date | tee -a ${Log} 2>&1; 
cd /blah/blah
sh ./somescript.ksh > logfile
exit" | tee -a ${Log} 2>&1;

The script tends to stop when it swicthes to USER1 and then it executes again when we have to exit manually.


I would expect that the script stops at the "su" command because it's prompting for a password and not getting one.

As often multiple solutions for that :)

Instead of "su" use "sudo" which has the -S switch to accept a password from standard input:

echo "password" | sudo -S -u USER1 sh -c "...

Alternatively move that section of your application/script that needs to run as a different user to a helper application. You can then avoid scripting with a stored clear text password (which has some security concerns) by using the set-uid and set-gid on that helper application:

chown USER1.GRP1 helperapp
chmod 6755 helperapp

The risk you run with this is that now anyone on the system can run helperapp as USER1. Instead of using set-uid/gid you can use configure sudo to allow a specific user to run het helperapp as USER1 without a password prompt (this requires admin/root priviliges):

# /etc/sudoers
# Allow USER2 to run helperapp as USER1 without prompting for a password
USER2 ALL=(USER1) NOPASSWD:/path/to/helperapp

your code can then look something like this:

(some code)
chown USER1 filename

sudo -u USER1  /path/to/helperapp |  tee -a ${Log} 2>&1;

None of this was tested and use at your own peril...

| improve this answer | |
  • You can add TCPMUX to the list. – kworr Sep 30 '13 at 14:19
  • This is only relevant if the script isn't running as root. Given that the script calls chown, it is highly likely to be running as root. – Gilles 'SO- stop being evil' Sep 30 '13 at 21:11
  • yes it runs as root – munish Oct 1 '13 at 3:12

Since you are running su -, you are telling su to run a login shell. A login shell ignored its -c argument and reads commands interactively instead. The solution is to not pass -.

If you want to read the target user's startup file, do that explicitly.

su - USER1 <<EOF
if [ -e ~/.profile ]; then . ~/.profile; fi
EOF 2>&1 | tee -a -- "$LOG"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.