title: Pass variables to remote script through SSH
body: <p>I am running scripts on a remote server from a local server via SSH. The script gets copied over using SCP in a first place, then called while being passed some arguments as follows:</p>
  
  <pre><code>scp /path/to/script server.example.org:/another/path/
  
  ssh server.example.org \
  MYVAR1=1 \
  MYVAR2=2 \
  /another/path/script
  </code></pre>
  
  <p>This works fine and on the remote server, the variables <code>MYVAR1</code> and <code>MYVAR2</code> are available with their corresponding value.</p>
  
  <p>The issue is that these scripts are in constant development which requires the SSH command to be changed every-time a variable is renamed, added, or removed.</p>
  
  <p>I'm looking for a way of passing all the local environment variables to the remote script (since <code>MYVAR1</code> and <code>MYVAR2</code> are actually local environment variables) which would address the SSH command maintenance issue.</p>
  
  <p>Since <code>MYVAR1=1 \</code> and <code>MYVAR1=1 \</code> are lines which follow the <code>env</code> command output I tried replacing them with the actual command as follows:</p>
  
  <pre><code>ssh server.example.org \
  `env`
  /another/path/script
  </code></pre>
  
  <p>This seems to work for "simple" <code>env</code> output lines (e.g. <code>SHELL=/bin/bash</code> or <code>LOGNAME=sysadmin</code>), however I get errors for more "complex" output lines (e.g. <code>LS_COLORS=rs=0:di=01;34:ln=01;[...]</code> which gives errors such as <code>-bash: 34:ln=01: command not found</code> ). I can get rid of these errors by unsetting the variables corresponding to those complex output lines before running the SSH command (e.g. <code>unset LS_COLORS</code>, then <code>ssh [...]</code>) however I don't find this very solution very reliable.</p>
  
  <p><strong>Q: Does anybody know how to pass all the local environment variables to a remote script via SSH?</strong></p>
  
  <p>PS: the local environment variables are not environment variables available on the remote machine <a href="https://stackoverflow.com/questions/216202/why-does-an-ssh-remote-command-get-fewer-environment-variables-then-when-run-manu">so I cannot use this solution</a>.</p>
  
  <p><strong>Update with solution</strong></p>
  
  <p>I ended using <code>sed</code> to format the <code>env</code> command output from <code>VAR=VALUE</code> to <code>VAR="VALUE"</code> (and concatenating all lines in to 1) which prevents bash from interpreting some of the output as commands and fixes my problem.</p>
  
  <pre><code>ssh server.example.org \
  `env | sed 's/\([^=]*\)=\(.*\)/\1="\2"/' | tr '\n' ' '` \
  "/another/path/script"
  </code></pre>