Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to export a variable inside a ssh session and reference the variable in the next write command.

sshpass -p "password" ssh -t -t my-box <<EOF
  export newUrl="this is a url"
  sudo -E sh -c 'echo "url=$newUrl" >> /path/to/file'
  exit
EOF

Instead of printing,

url=this is a url

to the file, it just prints,

url=

Why the variable's value is not accessible in the same ssh session?

share|improve this question
up vote 1 down vote accepted

Since the here-document is indicated by <<EOF (without any quotes), the content of the here-document is subject to expansion of \$`. Hence $newUrl in the here document expands to its value in the local shell.

To instead pass $newUrl to the remote shell and have it expand the variable, you can protect the $ from expansion: \$newUrl instead of $newUrl, or use a literal here-document: <<'EOF' instead of ``<

You're expanding the variable newUrl in a string which is going to be interpreted by a shell. This means that the value of the variable will be interpreted as a shell script fragment, not as a string. If the value contains shell special characters, havoc will ensue. (Which characters are problematic depends on which works-in-the-nominal-case solution you use.)

Instead of using many layers of quoting and expansion, pass the URL as input to the command running as root. Then you have nothing to worry about. This has the added advantage of working even if sudo is not configured to accept -E, which is fairly common. You can use sudo sh -c 'cat >>/path/to/file', or better, to avoid any potential quoting issues on the file, sudo tee -a /path/to/file.

sshpass -p "password" ssh -t -t my-box <<'EOF'
  newUrl="this is a url"
  printf '%s\n' "$newUrl" | sudo tee -a /path/to/file
EOF
share|improve this answer

Try to export with sudo. The variable gets lost when you sudo to another user. You can as well set Defaults env_keep += "newUrl" in your sudoers file in etc.

share|improve this answer
    
That's not the problem since Madhavan is using sudo -E. This would either work as intended or trigger an error. – Gilles Dec 20 '15 at 0:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.