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

标签 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

最佳答案

引用 -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/

相关文章:

c - 如何使用shell脚本比较两个文件,一个具有不同的字段,另一个是c文件?

linux - 使来自子进程的 shell 命令在父进程中执行(以锁定 shell)

macos - 在 bash 脚本中重试命令行直到成功,然后继续脚本

bash - 从 airodump-ng 读取实时输出

c++ - Cmake 奇怪的错误 : Syntax Error Unexpected Token ('

bash - 如何在 bash 中将星号字符 '*' 作为参数传递给我的 C 程序?

bash - 交换两个程序的输入和输出

bash - 如何检查符号链接(symbolic link)是否存在

bash - ffmpeg 脚本 mp4 到 mp3

bash - 如何删除 "TERM environment variable not set"