在 Bash 中 ssh 和运行多个命令的最干净的方法是什么? [英] What is the cleanest way to ssh and run multiple commands in Bash?

查看:31
本文介绍了在 Bash 中 ssh 和运行多个命令的最干净的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了 ssh 代理,我可以在外部服务器上使用 Bash 脚本运行命令,执行以下操作:

I already have an ssh agent set up, and I can run commands on an external server in Bash script doing stuff like:

ssh blah_server "ls; pwd;"

现在,我真正想做的是在外部服务器上运行大量长命令.将所有这些用引号括起来会非常难看,我真的宁愿避免多次 ssh 以避免这种情况.

Now, what I'd really like to do is run a lot of long commands on an external server. Enclosing all of these in between quotation marks would be quite ugly, and I'd really rather avoid ssh'ing multiple times just to avoid this.

那么,有没有一种方法可以一次性用括号或其他东西括起来呢?我正在寻找类似以下内容的内容:

So, is there a way I can do this in one go enclosed in parentheses or something? I'm looking for something along the lines of:

ssh blah_server (
   ls some_folder;
   ./someaction.sh;
   pwd;
)

基本上,只要是干净的,我都会对任何解决方案感到满意.

Basically, I'll be happy with any solution as long as it's clean.

澄清一下,我说的是这是一个更大的 bash 脚本的一部分.其他人可能需要处理脚本,所以我想保持干净.我不想让 bash 脚本看起来像一行:

To clarify, I'm talking about this being part of a larger bash script. Other people might need to deal with the script down the line, so I'd like to keep it clean. I don't want to have a bash script with one line that looks like:

ssh blah_server "ls some_folder; ./someaction.sh 'some params'; pwd; ./some_other_action 'other params';"

因为它极其丑陋且难以阅读.

because it is extremely ugly and difficult to read.

推荐答案

如何使用 Bash 此处文档:

How about a Bash Here Document:

ssh otherhost << EOF
  ls some_folder; 
  ./someaction.sh 'some params'
  pwd
  ./some_other_action 'other params'
EOF

为了避免@Globalz 在评论中提到的问题,您可以(取决于您在远程站点上执行的操作)将第一行替换为

To avoid the problems mentioned by @Globalz in the comments, you may be able to (depending what you're doing on the remote site) get away with replacing the first line with

ssh otherhost /bin/bash << EOF

请注意,您可以在 Here 文档中进行变量替换,但您可能需要处理引用问题.例如,如果您引用限制字符串"(即上面的 EOF),那么您就不能进行变量替换.但是没有引用限制字符串,变量被替换.例如,如果您在 shell 脚本中定义了上面的 $NAME,则可以执行

Note that you can do variable substitution in the Here document, but you may have to deal with quoting issues. For instance, if you quote the "limit string" (ie. EOF in the above), then you can't do variable substitutions. But without quoting the limit string, variables are substituted. For example, if you have defined $NAME above in your shell script, you could do

ssh otherhost /bin/bash << EOF
touch "/tmp/${NAME}"
EOF

它会在目标 otherhost 上创建一个文件,其名称为您分配给 $NAME 的任何名称.其他有关 shell 脚本引用的规则也适用,但太复杂了,无法在这里介绍.

and it would create a file on the destination otherhost with the name of whatever you'd assigned to $NAME. Other rules about shell script quoting also apply, but are too complicated to go into here.

这篇关于在 Bash 中 ssh 和运行多个命令的最干净的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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