简体   繁体   English

使用bash -c将所有args传递给在新shell中调用的命令

[英]Pass all args to a command called in a new shell using bash -c

I've simplified my example to the following: 我已将示例简化为以下内容:

file1.sh: file1.sh:

#!/bin/bash
bash -c "./file2.sh $@"

file2.sh: file2.sh:

#!/bin/bash
echo "first $1"
echo "second $2"

I expect that if I call ./file1.sh ab to get: 我希望如果我调用./file1.sh ab来获得:

first a
second b

but instead I get: 但是我得到了:

first a
second

In other words, my later arguments after the first one are not getting passed through to the command that I'm executing inside a new bash shell. 换句话说,第一个参数之后的我后面的参数不会传递给我在新的bash shell中执行的命令。 I've tried many variations of removing and moving around the quotation marks in the file1.sh file, but haven't got this to work. 我已经尝试了删除和移动file1.sh文件中的引号的许多变体,但是还没有奏效。

Why is this happening, and how do I get the behavior I want? 为什么会发生这种情况,如何获得所需的行为?

(UPDATE - I realize it seems pointless that I'm calling bash -c in this example, my actual file1.sh is a proxy script for a command that gets called locally to run in a docker container so it's actually docker exec -i mycontainer bash -c '' ) (更新-我意识到在这个例子中我叫bash -c似乎毫无意义,我的实际file1.sh是命令的代理脚本,该命令在本地被调用以在docker exec -i mycontainer bash -c ''容器中运行,因此实际上是docker exec -i mycontainer bash -c ''

Change file1.sh to this with different quoting: 用不同的引用将file1.sh更改file1.sh

#!/bin/bash
bash -c './file2.sh "$@"' - "$@"

- "$@" is passing hyphen to populate $0 and $@ is being passed in to populate all other positional parameters in bash -c command line. - "$@"传递连字符以填充$0$@则传递以填充bash -c命令行中的所有其他位置参数。

You can also make it: 您也可以做到:

bash -c './file2.sh "$@"' "$0" "$@"

However there is no real need to use bash -c here and you can just use: 但是,这里并不需要真正使用bash -c ,您可以使用:

./file2.sh "$@"

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

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