How can i set a local variable in ssh?

2019-08-15 02:02发布

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.

标签: ssh
2条回答
ら.Afraid
2楼-- · 2019-08-15 02:21

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'"
查看更多
叼着烟拽天下
3楼-- · 2019-08-15 02:33

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'
查看更多
登录 后发表回答