bash 在多行上编写 SSH 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32082646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:27:13  来源:igfitidea点击:

Write SSH command over multiple lines

bashshellsshremote-access

提问by dspshyama

I'm trying to remote login to a shell and execute a bunch of commands on the shell. But to make it more readable, I'd like to place my code over multiple lines. How should I be doing this?

我正在尝试远程登录到 shell 并在 shell 上执行一堆命令。但为了使其更具可读性,我想将我的代码放在多行上。我该怎么做?

ssh -o <Option> -x -l <user> <host> " $long_command1; $long_command2; ....  "

Thanks!

谢谢!

采纳答案by Alfe

sshis in fact just passing a string to the remote host. There this string is given to a shell which is supposed to interpret it (the user's login shell, which is typically something like bash). So whatever you want to execute needs to be interpretable by that remote login shell, that's the whole rule you have to stick to.

ssh实际上只是将字符串传递给远程主机。这个字符串被提供给一个应该解释它的shell(用户的登录shell,通常类似于bash)。因此,无论您想执行什么,都需要能够被远程登录 shell 解释,这就是您必须遵守的整个规则。

You can indeed just use newlines within the command string:

您确实可以在命令字符串中使用换行符:

ssh alfe@sweethome "
  ls /home/alfe/whatever
  ping foreignhost
  date
  rm foobar
"

回答by ntki

You can use the Here Documentsfeature of bash. It is like:

您可以使用Here Documents的功能bash。它像是:

ssh <remote-host> bash <<EOF
echo first command
echo second command
EOF

EOF marks the end of the input.

EOF 标志着输入的结束。

For further info: use man bashand search for Here Documents.

欲了解更多信息:使用man bash并搜索Here Documents.

Edit: The only caveat is that using variables can be tricky, you have to escape the $to protect them to be evaluated on the remote host rather then the local shell. Like \$HOSTNAME. Otherwise works with everything that is run from bash and uses stdin.

编辑:唯一需要注意的是,使用变量可能会很棘手,您必须转义$以保护它们在远程主机上而不是本地外壳上进行评估。喜欢\$HOSTNAME。否则适用于从 bash 运行并使用stdin.

回答by crafter

You can do like in the following example.

您可以在以下示例中执行操作。

ssh -o <Option> -x -l <user> <host> '
pwd
whoami
ls
echo "$PATH"
'