gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:12:14 26 4
gpt4 key购买 nike

我正在编写一个 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

最佳答案

引用 -c 的 bash 手册:

If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $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 位?

关于bash - 通过 bash 脚本将参数传递给/bin/bash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12059528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com