将远程变量的值分配给 unix/linux 中的局部变量 [英] Assigning the value of a remote variable to a local variable in unix/linux

查看:24
本文介绍了将远程变量的值分配给 unix/linux 中的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个远程变量,我想将其值分配给 unix 中的局部变量.这是代码#!/bin/bash

I am creating a remote variable whose value I want to assign to a local variable in unix. Here is the code #!/bin/bash

INPUT= "test"
ssh username@domain.com
"if [ -s $INPUT ];
then
    date=\`date\`
    remote= $INPUT.date
    $INPUT= \$remote
else
    mkdir $INPUT
fi"

基本上我是给一个局部变量赋值.在通过 ssh 连接到远程服务器时,我正在检查是否存在名为test"的非空目录.如果是,那么我将时间戳附加到 $INPUT 局部变量.代码工作正常,直到第 8 行remote= $INPUT.date".但是远程变量 \$remote 到局部变量 $INPUT 的赋值没有.我究竟做错了什么.感谢您的帮助.

Basically I am assigning a value to a local variable. Upon ssh to a remote server, I am checking whether a non-empty directory by the name of "test" exists. If it does, then I am appending a time-stamp to the $INPUT local variable. The code works fine till line 8 "remote= $INPUT.date". But the assignment of the remote variable \$remote to the local variable $INPUT does not. What am I doing wrong. Thanks for the help.

推荐答案

正如 Rup 所说,远程 shell 无法设置您的本地 shell 变量.您需要通过打印出来并使用命令替换来捕获远程变量.这个 SSH 命令会做你想做的事情,然后它会回显你想要存储在 $INPUT 中的修改值:

As Rup said, the remote shell cannot set your local shell variables. You need to capture the remote variable by printing it out, and using command substitution. This SSH command will do what you are trying to do, then it will echo the amended value you want to store in $INPUT:

INPUT="test"
ssh user@remotehost "if [ -s $INPUT ]; then 
timestamp=\$(date)
echo "${INPUT}.\${timestamp}"
fi"

输出:

test.Monday, 24 February 2014 11:26:41 GMT

如果您想更改 $INPUT,则需要使用整个 SSH 命令作为命令替换:

If you want $INPUT to be changed, you then need to use the whole SSH command as a command substitution:

INPUT="test"
INPUT=$(ssh user@remotehost "if [ -s $INPUT ]; then 
timestamp=\$(date)
echo "${INPUT}.\${timestamp}"
fi")

输出:

$> echo $INPUT
test.Monday, 24 February 2014 11:27:47 GMT

同样,如果你想将一个变量存储在一个 txt 文件中,这会将它存储在远程主机上:

Similarly, if you want to store a variable in a txt file, this will store it on the remote host:

ssh user@remotehost "echo \$remote > file.txt"

这会将其存储在本地:

ssh user@remotehost "echo \$remote" > file.txt

这篇关于将远程变量的值分配给 unix/linux 中的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆