如何将提供给 bash 脚本的所有命令行参数(包括字符串参数)原样传递给子进程?
How do I pass all command line arguments given to a bash script including string parameters as-is to a child process?
以下问题是我的问题的变体:
Bash: Reading quoted/escaped arguments correctly from a string
我想编写以下类型的 bash 脚本(例如 'something.sh')...
#!/bin/bash
python $*
... 将所有命令行参数直接传递给子进程。以上基于 $* 适用于像 ...
这样的命令
./something.sh --version
...就好了。但是,对于字符串参数,例如在这种情况下,它惨遭失败......
./something.sh -c "import os; print(os.name)"
... 结果(在我的示例中)...
python -c import
... 在第一个 space 处剪切字符串参数(自然会产生 Python 语法错误)。
我正在寻找一个通用解决方案,它可以处理 bash 脚本调用的任意程序的多个参数和字符串参数。
你需要使用$@
,并引用它
#!/bin/bash
python "$@"
使用这个:
python "$@"
$@
和 $*
都扩展到脚本收到的所有参数,但是当您使用 $@
并将其放在双引号中时,它会自动重新引用所有内容,因此它工作正常。
来自bash manual:
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@"
is equivalent to "" "" …
.
另见 Why does $@ work different from most other variables in bash?
以下问题是我的问题的变体:
Bash: Reading quoted/escaped arguments correctly from a string
我想编写以下类型的 bash 脚本(例如 'something.sh')...
#!/bin/bash
python $*
... 将所有命令行参数直接传递给子进程。以上基于 $* 适用于像 ...
这样的命令./something.sh --version
...就好了。但是,对于字符串参数,例如在这种情况下,它惨遭失败......
./something.sh -c "import os; print(os.name)"
... 结果(在我的示例中)...
python -c import
... 在第一个 space 处剪切字符串参数(自然会产生 Python 语法错误)。
我正在寻找一个通用解决方案,它可以处理 bash 脚本调用的任意程序的多个参数和字符串参数。
你需要使用$@
,并引用它
#!/bin/bash
python "$@"
使用这个:
python "$@"
$@
和 $*
都扩展到脚本收到的所有参数,但是当您使用 $@
并将其放在双引号中时,它会自动重新引用所有内容,因此它工作正常。
来自bash manual:
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is,
"$@"
is equivalent to"" "" …
.
另见 Why does $@ work different from most other variables in bash?