1

I've got the following in a bash script

ssh -T -i ${ssh_key} ${ssh_user}@${host} <<- 'EOF'
  file=`hostname`.tar.gz
  echo "file: " $file 
  ### prints>> file: some-host-name.tar.gz 
EOF

scp -i ${ssh_key} ${ssh_user}@${host}:${file} ~/incoming
### prints>> scp -i /home/user/.ssh/key.pem user@192.168.1.1: ~/incoming

I'm trying to set the filename inside the heredoc, as it's based on the host I'm connecting to. I then want to use that filename to scp the file to another location, but I can't get the filename outside of the heredoc.

Suggestions?

  • You have quoted 'EOF', no expansion was performed in body of here-document. Anyway, variable assignment was not performed inside here-document. – cuonglm Sep 23 '15 at 7:00
  • file variable is being assigned in sub shell created for SSH session. Parent shell is unable to access those variables.. You can go with solution mentioned by @muru – AVJ Sep 23 '15 at 13:50
2

It's not a matter of heredocs. If you'd run:

ssh -i ${ssh_key} ${ssh_user}@${host} sh -c '
  file=`hostname`.tar.gz
  echo "file: " $file
'

The effect would have been the same. Point being: variable is evaluated in the shell started by SSH on the remote server. There's nothing it can do to affect a variable on the local shell.

So, instead, do:

file=$(ssh -i ${ssh_key} ${ssh_user}@${host} hostname).tar.gz
scp -i ${ssh_key} ${ssh_user}@${host}:${file} ~/incoming
  • Thanks for the explanation and for providing the alternative, that's exactly what I needed. – richj Sep 23 '15 at 18:19

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.