Issue
I was trying to execute a ssh
command and I see it takes environment variable from the host (local) machine rather than the machine I ssh
into (remote server).
Example:
firstuser@remote> ssh testuser@remote echo ${USER}
firstuser
It was expecting it to echo testuser instead of firstuser as it is the username I connected with.
If it can help, I am using CentOS7.
Any thoughts/explanations on this specific issue?
Solution
If I understand this correctly, you are getting the variable ${USER}
from the host (local) machine not from the SSH (remote) server. This is because you are executing it all in one command. Your command is being processed locally - meaning the variable is being substituted - before being sent to the remote (SSH) server.
You can solve this by passing the command as a string that will not be translated/processed/substituted locally to, in your case, firstuser
, or whichever other previously declared variable.
firstuser@mymachine> ssh testuser@mymachine 'echo ${USER}'
Important note here is that echo ${USER}
is in single quotes, it will not work with double quotes. This is basic bash/shell rule but as a courtesy, you can find out more about this at https://missing.csail.mit.edu/2020/shell-tools/#shell-scripting
In a nutshell, when a variable is being processed/interpreted/substituted locally as you are trying to do, the remote SSH server receives the litteral: echo firstuser
not echo ${USER}
, which would be processed remotely, as intended.
Answered By - Adriel Sand Answer Checked By - Robin (WPSolving Admin)