How to pass local shell script variable to expect?

2019-09-18 02:11发布

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?)
'

2条回答
Animai°情兽
2楼-- · 2019-09-18 02:32

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

查看更多
\"骚年 ilove
3楼-- · 2019-09-18 02:56

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)"'
查看更多
登录 后发表回答