0

I have a script doing something like this:

var1=""
ssh xxx@yyy<<'EOF'
[...]
var2=`result of bash command`
echo $var2 #print what I need
var1=$var2 #is there a way to pass var2 into global var1 variable ?
EOF

echo $var1  # the need is to display the value of var2 created in EOF block

Is there a way to do this?

2
  • 2
    How can this happen, the commands inside here-doc are run in a shell on a remote server and var1 is defined in the shell on your local machine Commented Jan 4, 2018 at 10:29
  • note: if I remote the '' on EOF, the var2 is no longer available inside the block Commented Jan 4, 2018 at 10:32

1 Answer 1

3

In general, an executed command has three paths of delivering information:

  1. By stating an exit code.
  2. By making output.
  3. By creating files.

It is not possible to change a (environment) variable of the parent process. This is true for all child processes, and your ssh process is no exemption.

I would not rely on ssh to pass the exit code of the remote process, though (because even if it works in current implementations, this is brittle; ssh could also want to state its own success or failure with its exit code, not the remote process's).

Using files also seems inappropriate because the remote process will probably have a different file system (but if the remote and the local machine share an NFS for instance, this could be an option).

So I suggest using the output of the remote process for delivering information. You could achieve this like this:

var1=$(ssh xxx@yyy<<'EOF'
[...]
var2=$(result of bash command)
echo "$var2" 1>&2 # to stderr, so it's not part of the captured output
                  # and instead shown on the terminal
echo "$var2"      # to stdout, so it's part of the captured output
EOF
)

echo "$var1"
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Alfe, sorry, my mistakes, but it seems not working as expected : output is like this :\n ./file.bash: rowxx : warning :« here-document » on line 32 delimited by end of file (instead of « EOF »)\n value of $var2 with assignation 1>&2\n value of $var1 (begins with "Linux xxxx ... The programs included with the Debian GNU/Linux system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright.\n [...], but without any value of $var2\n value of $var2 without assignation (just before the EOF)
Alfer, after some test, here how I found a workaround : echo $var2 EOF) var3=echo "$var1" | tail -n 1 regards. echo "Et voila le fichier : $bkp_file"

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.