简体   繁体   English

通过标准输入将带有 arguments 的脚本作为字符串传递给 bash

[英]Pass a script with arguments via stdin as a string to the bash

Currently I'm having an issue to pass a script with arguments to the bash.目前,我在将带有 arguments 的脚本传递给 bash 时遇到问题。 The limitation is that I can pass them as a string (see $COMMAND)限制是我可以将它们作为字符串传递(参见 $COMMAND)

ssh user@server 'bash -s' < "$COMMAND"

if my $COMMAND contains "foo.sh bar baz", I would get error no such file or directory: foo.sh bar baz如果我的 $COMMAND 包含“foo.sh bar baz”,我会得到错误no such file or directory: foo.sh bar baz

Additionally, I'm be able to set additional options to bash.此外,我可以为 bash 设置其他选项。

Thank you in advance!!!先感谢您!!!

The root problem is that < takes a filename to redirect from, not a filename and some arguments.根本问题是<需要一个文件名来重定向,而不是文件名和一些 arguments。 Mixing the two together this way just won't work.以这种方式将两者混合在一起是行不通的。

If I'm understanding right, you want to run a script that exists on the local computer, but have it execute (with the supplied arguments) on the remote computer.如果我理解正确,您想运行本地计算机上存在的脚本,但让它在远程计算机上执行(使用提供的参数)。 In that case, what you want to run is something like this:在这种情况下,你想要运行的是这样的:

ssh user@server 'bash -s bar baz' <"foo.sh"

Note that the arguments are passed in a completely different place than the script filename.请注意,arguments 在与脚本文件名完全不同的位置传递。 If possible, I'd recommend never mixing the two;如果可能的话,我建议不要将两者混为一谈; keep them in separate variables, and then use something like this:将它们保存在单独的变量中,然后使用如下内容:

ssh user@server "bash -s $scriptargs" <"$scriptfile"

From the sounds of the error, foo.sh doesn't exist on server, so it fails.从错误的声音来看, foo.sh在服务器上不存在,所以它失败了。

The simplest solution seems to be:最简单的解决方案似乎是:

ssh user@server 'foo.sh bar baz' , provided "foo.sh" exists on the server. ssh user@server 'foo.sh bar baz' ,前提是服务器上存在“foo.sh”。

If "foo.sh" doesn't/can't exist on the server, have you tried using here docs ?如果服务器上不存在/不存在“foo.sh”,您是否尝试过使用此处的文档 For example:例如:

ssh user@server "cat > foo.sh && chmod u+x foo.sh && ./foo.sh bar baz" << "EOF"
`heredoc> #Put your contents of foo.sh here
`heredoc> #And put them here
`heredoc> echo "Argument 1: $1"
`heredoc> echo "Argument 2: $2"
`heredoc> EOF
user@server's password:
Argument 1: bar
Argument 2: baz

EDIT:编辑:

david@localhost ~ % bash -s < test.sh David Finder
Hello David
Hello Finder

Edit to my previous answer, the issue is due to the quoting of the input arguments thrown to Bash, as it sees the entire input as one file (it's looking for a file literally called "foo.sh bar baz", with spaces within.编辑我之前的答案,问题是由于引用了输入 arguments 引发的 Bash,因为它将整个输入视为一个文件(它正在寻找一个字面上称为“foo.sh bar baz”的文件,其中包含空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM