通过bash脚本将参数传递给/ bin / bash

时间:2012-08-21 16:49:36

标签: bash

我正在编写一个bash脚本,它接受许多命令行参数(可能包括空格)并通过登录shell将它们全部传递给程序(/ bin / some_program)。从bash脚本调用的登录shell将取决于用户的登录shell。假设用户在此示例中使用/ bin / bash作为其登录shell ...但它可能是/ bin / tcsh或其他任何内容。

如果我知道将多少个参数传递给some_program,我可以在我的bash脚本中添加以下行:

#!/bin/bash
# ... (some lines where we determine that the user's login shell is bash) ...
/bin/bash --login -c "/bin/some_program \"$1\" \"$2\""

然后按如下方式调用上面的脚本:

my_script "this is too" cool

通过上面的例子,我可以确认some_program收到两个参数,“这太”和“酷”。

我的问题是......如果我不知道会传递多少参数怎么办?我想将发送到my_script的所有参数传递给some_program。问题是我无法弄清楚如何做到这一点。以下是不起作用的一些内容

/bin/bash --login -c "/bin/some_program $@"     # --> 3 arguments: "this","is","too"
/bin/bash --login -c /bin/some_program "$@"     # --> passes no arguments

2 个答案:

答案 0 :(得分:4)

引用-c的bash手册:

  

如果存在-c选项,则从字符串中读取命令。如果字符串后面有参数,则会将它们分配给位置参数,以$ 0开头

适合我:

$ cat x.sh
#!/bin/bash
/bin/bash --login -c 'echo 1:$1 2:$2 3:$3' echo "$@"
$ ./x.sh "foo bar" "baz" "argh blargh quargh"
1:foo bar 2:baz 3:argh blargh quargh

我不知道你是如何得出“通过无论证”的结论,也许你错过了$0位?

答案 1 :(得分:0)

避免将变量嵌入到其他脚本中,而是将它们作为参数传递。在这种情况下:

bash --login -c 'some_program "$@"' some_program "$@"

-c'...'之后的第一个参数被视为$ 0,所以我只是在那里输入some_program。

另一方面,要求登录shell是一项奇怪的要求。用户不登录吗?