我有一个包装脚本,它做了一些工作,然后将原始参数传递给另一个工具:
#!/bin/bash
# ...
other_tool -a -b "$@"
Run Code Online (Sandbox Code Playgroud)
这工作正常,除非“其他工具”在子shell中运行:
#!/bin/bash
# ...
bash -c "other_tool -a -b $@"
Run Code Online (Sandbox Code Playgroud)
如果我像这样调用我的包装脚本:
wrapper.sh -x "blah blup"
Run Code Online (Sandbox Code Playgroud)
然后,只有第一个原始参数 (-x) 被传递给“other_tool”。实际上,我没有创建子外壳,而是将原始参数传递给 Android 手机上的外壳,这应该没有任何区别:
#!/bin/bash
# ...
adb sh -c "other_tool -a -b $@"
Run Code Online (Sandbox Code Playgroud)
Gor*_*son 17
Bash 的printf命令具有引用/转义/任何字符串的功能,因此只要父 shell 和子 shell 实际上都是 bash,这应该可以工作:
[编辑:正如 siegi 在评论中指出的那样,如果你这样做很明显,当没有提供参数时就会出现问题,它的作用就像实际上只有一个空参数一样。我在下面添加了一个解决方法,用 包装格式字符串${1+},如果定义了第一个参数,则只包含格式字符串。这有点笨拙,但确实有效。]
#!/bin/bash
quoted_args="$(printf "${1+ %q}" "$@")" # Note: this will have a leading space before the first arg
# echo "Quoted args:$quoted_args" # Uncomment this to see what it's doing
bash -c "other_tool -a -b$quoted_args"
Run Code Online (Sandbox Code Playgroud)
请注意,您也可以在一行中完成: bash -c "other_tool -a -b$(printf "${1+ %q}" "$@")"
| 归档时间: |
|
| 查看次数: |
25532 次 |
| 最近记录: |