简体   繁体   中英

How to access environment variables in an Expect script?

I would like to access the PATH environment variable inside an expect script.

How can I achieve that?

My actual script is:

#!/usr/bin/expect
set timeout 300
send "echo $PATH\r"

and its ouput is:

can't read "PATH": no such variable
    while executing
"send "echo $PATH\r""

Expect is an extension of Tcl . Tcl access enviroment variables via the global env array :

send_user "$env(PATH)\n"

You can use the global env array by using:

$::env(PATH)    

This notion will also work inside procedures.

If you want to read the target $PATH variable, then you must escape the "$" :

exp_sent -- echo "\\$PATH\\r"

Both $::env(PATH) and $env(PATH) work well. The former is ok also inside other scripts (like expect -c "..." , the latter is more "programming style".

If I have a variable inside my shell script like:

PASSWORD="ADSJAKJADSD"

How can I make expect read it without having to export the variable like: export PASSWORD=$PASSWORD

/usr/bin/expect <<'END_EXPECT'
    set timeout -1
    log_file  expect-log.txt
    spawn -noecho sh somecommand
    expect "yes" { send "yes\r"}
    expect {
        -nocase "*assword*" {
            send "$env(PASSWORD)\r"
            exp_continue
        }
    send \r
        eof
    }
END_EXPECT

On the expect code above, if I run it without exporting the variable then it doesn't work, it says the variable couldn't be read. If I export the variable, then it works fine. However due to security reasons I can't export this variable to all child process.

Anyone has any idea?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM