SSH: Use Remote Bash / KSH source Command Set Variable Locally From a Remote Server

You can use the remote source command with the ssh command to set a variable locally from a remote server. Here’s an example in bash:

VAR=$(ssh user@remote-server "source ~/.bashrc; echo \$VAR")

In this example, the ssh command connects to the remote server as user, sources the ~/.bashrc file, and then echoes the value of the VAR variable. The output of the remote command is captured and stored in the local VAR variable.

You can replace ~/.bashrc with the path to any file that sets the desired variable on the remote server. The same method can be used with ksh or any other shell that supports the source command.

Leave a Comment