如何在一个 ssh 命令中传递多个指令?

如何在一个 ssh 命令中传递多个指令?

我遇到了一个问题,这个问题困扰了我一段时间。我做了很多研究,得到了不少答案,但这些答案似乎不适合我的情况。这就是我想要做的:

通过 ssh 命令,我希望能够运行将在远程服务器上运行的多个命令。下面是我正在尝试执行的操作的示例,并附有我的说明。

在包含参数的脚本中,我想运行 ssh 同时传递名为 $SSH_CMD 的变量中包含的指令列表:

ssh -tv $IP "$SSH_CMD";

变量设置如下:

    SSH_CMD="$(cat <<-EOF
        
        touch $DIR/test0.txt;
        if [ -d $DIR ]; then
                touch $DIR/test1.txt;
                if [[ -n $(find $DIR -type f -mtime +7) ]]; then
                        touch $DIR/test2.txt;
                        sudo find $DIR -name abc -type f -mtime +7 -delete;
                fi
        else
                touch $DIR/test3.txt;
        fi
        touch $DIR/test4.txt;
        EOF
        
    )"

感谢详细帮助,我在运行脚本时能够得到这个:

    debug1: Sending command:
        
            touch /a_random_dir/test0.txt;
            if [ -d /a_random_dir ]; then
                touch /a_random_dir/test1.txt;
                if [[ -n  ]]; then
                    touch /a_random_dir/test2.txt;
                    sudo find /a_random_dir -name abc -type f -mtime +7 -delete;
                fi
            else
                touch /a_random_dir/test3.txt;
            fi
        
    bash: -c: line4: unexpected argument "]]" for one-argument conditional operator
    bash: -c: line4: Syntax error near « ; »
    debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
    debug1: client_input_channel_req: channel 0 rtype [email protected] reply 0
    bash: -c: line4: `if [[ -n  ]]; then'

您应该知道,出于测试目的,我使用创建的 .txt 来了解脚本经过了哪条“路径”。这里我只有创建的“test0.txt”。我们可以看到,整个“$(find $DIR -type f -mtime +7)”都消失了,“test4.txt”也是如此。除了遇到的错误之外,我觉得第一个“if”遇到了问题,因为我指出了两种可能的情况(如果目录存在,如果不存在),但 test1.txt 和 test3.txt 都没有创建。知道为什么吗?

我故意从脚本中删除了一些段落,以便您更容易理解,但是请知道我需要保留条件(如果)。

我提前感谢您给予我的任何帮助。

答案1

好的,我了解了问题的根源以及如何解决它。

这里绝对所有遇到的问题都和这段话有关: if [[ -n $(find $DIR -type f -mtime +7) ]

正如向我解释的那样,$() 由本地 shell(在我的情况下是远程服务器)扩展,而事实上,我希望在远程服务器上执行命令之前,在脚本执行时直接解释所有这些命令。

为了解决这个问题,我用引号替换了 $(),现在它可以按预期工作了。

感谢大家的帮助,希望这也能帮助未来的创作者。

祝你美好的一天。

相关内容