Take the 2-minute tour ×

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


su - testuser <<- _EOF_
    123456 #password

ls -lih

here is the output when i ran script:

-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

    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
share|improve this answer
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


