Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

here is my script. I want to login with another user and do ls -lih:

#!/bin/bash

su - testuser <<- _EOF_
    123456 #password
    _EOF_

ls -lih

here is the output when i ran script:

./script.sh
-bash: line 1: 123456: command not found
total 127M
 262210 drwxr-xr-x.  9 mazimi mazimi 156K Feb 14 19:05 Desktop
 262211 drwxr-xr-x.  2 mazimi mazimi  36K Feb 14 18:26 Downloads
 278106 -rw-r--r--   1 mazimi mazimi  64K Feb 14 22:30 ems.cfg
 ... # list of files

It does ls -lih in my home directory not testuser? How should I fix it?

share|improve this question
    
So the su actually works? –  Michael Mrozek Feb 14 '12 at 19:25

3 Answers 3

up vote 5 down vote accepted

There are several problems with your code.

  1. su reads the password from /dev/tty, not from stdin, so you can't redirect the password like this. In fact, what su does by default is start a shell as the target user, so if you run this as root:

    su - testuser <<- _EOF_
    123456 #password
    _EOF_
    

    The su will succeed (root doesn't need a password to do this), but the 123456 will get passed as input to the user's shell, which is why when you run your script you see:

    -bash: line 1: 123456: command not found
    

    If you want to do this as a non-root user, you should probably follow bahamt's advice and use sudo, which can be configured to offer password-free access to specific commands as a different user.

  2. Even if the su works, it spawns a new process. The su command has exited (and returned to the original account) before the ls command executes. So what you really want is:

    su - testuser <<EOF
    ls -lih
    EOF
    
share|improve this answer
1  
You could use something like script (the utility called script, not write a script), to wrap around su, but thats a hack. A really ugly hack. Agree with sudo –  Patrick Feb 15 '12 at 0:01

I think you'll find that you can't fix it. I think that su reads /dev/tty for the password, and I believe you can't really redirect to that magic device file.

If you're using linux, you can verify what su reads for the password with strace.

share|improve this answer

What you actually want to use is sudo.

You might want to start here.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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