0

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
  • 1
    expect -c ' .... '"$d"'......' ? Good luck. Commented Dec 9, 2014 at 21:29

2 Answers 2

3

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)"'
Sign up to request clarification or add additional context in comments.

1 Comment

In this case I'm building another date. I want to use the date that the shell script generated..
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

5 Comments

note: I already have double quotes several times inside the expect block
You can replace nested " by \042
Maybe there's better solutions, what are you trying to do ?
I'm using the local shell variable $d inside this script directly and running it now. I'll post in the next few mins when it completes.
This seems the wrong way to do things. You should set up SSH keys (with ssh-keygen and ssh-copy-id), google about this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.