How to pass a value from bash into expect?

I've got a really simple bash script which requires expect. I need to pass a value from bash into expect and I'm not trying to ssh into another server or anything (cause I only seem to find questions regarding logging into another server via ssh).

The idea is simply something like this:

#!/usr/bin/env bash

echo "Please enter your password: "

x=$(expect -c '
    spawn su -c 'whoami'
    expect "Password:"
    send "$PASSWD\r"

So this doesn't work. The expect shell doesn't recognize the $PASSWD variable. How may this be accomplished?

Thank you.


Another option would be to store the PASSWD in the environment and let expect pick it up there:

read -p "Your password: " passwd
export passwd

expect -c '... ; send "$env(passwd)\r"; ...'

Probably the best choice security-wise is have expect prompt for the password: then, the password will not show up on the command line nor in the environment.

expect -c <<'END'
    stty -echo 
    send_user "Your password: " 
    expect_user -re "(.*)\n" 
    send_user "\n" 
    set passwd $expect_out(1,string)
    stty echo 

    # your script starts here
    send "$passwd\r"

Variables within single quotes are not expanded by the shell, that's why in this case $PASSWD remains the literal string $PASSWD.

Try changing the quotes:

#!/usr/bin/env bash

echo "Please enter your password: "

x=$(expect -c "
    spawn su -c 'whoami'
    expect 'Password:'
    send '$PASSWD\r'

One more note: you should be aware that this could pose a security risk, as the password will be visible in plaintext in the process list while the command is running.

Need Your Help

Select 3 elements using XPath with namespace but filter it by attribute (Firefox Only)

xml xpath xsd namespaces

I've got a Blog structure XML with namespaces. I don't have any problem printing all the posts title, date and content - Although it only works properly on Firefox (only tested on version 35).

How can I show scrollbars on a System.Windows.Forms.TextBox only when the text doesn't fit?

winforms textbox scrollbar

For a System.Windows.Forms.TextBox with Multiline=True, I'd like to only show the scrollbars when the text doesn't fit.