inselberg
inselberg

Reputation: 959

How can i set a local variable in ssh?

I would like to set a local variable in a ssh command-chain that is only used in this environment:

#!/bin/sh
my_var='/tmp/wrong_file'
ssh user@server "my_var='/tmp/a_file'; cat $my_var;my_var=123;echo $my_var"
echo $my_var

This example the "outer" $my_var is used. How to fix this and use variables "in" the current ssh connection as locally defined? There is no need to change or access the external value '/tmp/wrong_file' in $my_var, as asked in Assign directory listing to variable in bash script over ssh.

Upvotes: 4

Views: 16101

Answers (2)

Jens
Jens

Reputation: 72639

You're using the wrong quotes. Parameter expansion is performed inside double quotes, but not inside single quotes.

#!/bin/sh
my_var=/tmp/wrong_file
ssh user@server 'my_var=/tmp/a_file; cat $my_var;my_var=123;echo $my_var'

Upvotes: 2

Eugen Rieck
Eugen Rieck

Reputation: 65264

First of all: The SSH shell and your local shell are completely different and do not exchange any environment variables. This is a good thing - consider environment variables such as LD_LIBRARY_PATH when using SSH between machines of different OS architecture.

IMHO the best solution for your problem is to encapsulate your commands into a shell script on the remote side, then maybe start it with parameters. E.g.:

Remote:

myscript.sh contains:

#!/bin/sh
MY_FILE="$1";
echo "Contents of §MY_FILE:"
cat $MY_FILE

Local:

RUn something like

export REMOTE_FILE='/path/to/it'
ssh user@server "/path/to/myscript.sh '$REMOTE_FILE'"

Upvotes: 0

Related Questions