3

I'm running an expect script and the password has a $ character. The shell looks for the following characters to expand into something and spits out no such variable.

Is there any way around this?

  • 1
    show the code where you're sending the password. – glenn jackman Dec 19 '16 at 22:57
6

There are two ways; either backslash each and every special character, or instead use curly braces around the password:

expect1.1> set pass "\$Hunter2"
$Hunter2
expect1.2> set pass {$Hunter2}
$Hunter2

Three! Three ways: the password can be read from the file thepasswordfile; this has the advantage of the password not being in the code:

#!/usr/bin/env expect

# wrap with catch(n) or try(n) if you don't want an error to abort 
# the code...
set fh [open thepasswordfile]
set password [gets $fh]

puts $password

Four, collect the password from a program that produces it on standard output:

#!/usr/bin/env expect

if {[catch {exec ./getthepassword} results options]} {
    puts $results
    exit 1
}

puts $results

Which might look something like:

$ cat fromstdin 
#!/usr/bin/env expect

if {[catch {exec ./getthepassword} results options]} {
    puts $results
    exit 1
}

puts $results

$ cat getthepassword 
#!/bin/sh
echo '$Hunter2'

$ chmod +x fromstdin getthepassword
$ ./fromstdin 
$Hunter2
$ 

Five! Five ways, the password can also be read from the environment (environ(7), tclvars(n))

#!/usr/bin/env expect
set password $env(pass)
puts $password

assuming an export pass='$Hunter2' or equivalent has been done in the parent process prior to calling this implementation. Downside: environment variables get passed to any and all child processes, which may or may not need to have rights to view the password. If in doubt, unset the variable after using or copying it:

#!/usr/bin/env expect
set password $env(pass)
unset env(pass)
...
0

I had a similar issue where I wanted to pass fileName with $ in expect script and following worked for me

filePath=$(echo -n $filePath | sed -e 's/\$/\\\$/g')

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.