2

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?

Majid Azimi
  • 3,098

3 Answers3

6

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
    
larsks
  • 34,737
  • 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 – phemmer Feb 15 '12 at 00:01
1

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.

1

What you actually want to use is sudo.

You might want to start here.

bahamat
  • 39,666
  • 4
  • 75
  • 104