How to pass local shell script variable to expect?

天大地大妈咪最大 提交于 2019-12-25 01:48:16

问题


My question is related to How to pass variables from a shell script to an expect script?

but its slightly different:

Apart from passing two runtime shell script variables, I want to pass a variable thats inside the shell script For eg:

#!/bin/sh
d=`date '+%Y%m%d_%H%M'`

expect -c '
expect "sftp>"


#use $d here(how?)
'

回答1:


You don't need to pass a date variable into expect. It has a very good date command builtin:

expect -c '

# ...

set d [timestamp -format "%Y%m%d_%H%M"]
something_with $d

# ...
'

If you need to do more complicated date manipulation, read about the Tcl clock command


Another good technique to pass shell variables to expect (without having to do complicated/messy quoting/escaping) is to use the environment: export your shell variables, and then access them with expect's global env array:

export d=$(date ...)

expect -c 'puts "the date is $env(d)"'



回答2:


This seems the wrong way to do things. You should set up SSH keys (with ssh-keygen and ssh-copy-id), google about this.

Anyway, try this :

#!/bin/sh
d=`date '+%Y%m%d_%H%M'`

expect -c "

something_with $d"

Note the double quotes instead of single quotes.

"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See http://mywiki.wooledge.org/Quotes , http://mywiki.wooledge.org/Arguments and http://wiki.bash-hackers.org/syntax/words



来源:https://stackoverflow.com/questions/27389113/how-to-pass-local-shell-script-variable-to-expect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!