我有一个脚本,当直接调用时,它可以使用以下参数组合正常工作:
--path=/path/to/a\ folder\ with\ spaces
--path='/path/to/a folder with spaces'
--path="/path/to/a folder with spaces"
但我很难将参数从辅助脚本传递给它。
我尝试了很多事情,但在每种情况下,我的脚本都好像收到以下内容:--path=/path/to/a folder with spaces
这让我的脚本感到困惑,它就像如果 /path/to/a
是路径(即 --path 的参数)和 folder
with
spaces
是附加参数。
作为一个最小的例子,以下都不会产生所需的结果(将以下内容保存到所需的工作目录中,如 ./so_example.sh
和 chmod +x ./so_example.sh
):
#!/usr/bin/env bash
set -x
printf "%s\n" "$@"
echo "$@"
echo -e "$@"
printf "%s\n" $@
echo $@
echo -e $@
当有以下几种方式调用时:
./so_example.sh --path=/path/to/a\ folder\ with\ spaces
./so_example.sh --path='/path/to/a folder with spaces'
./so_example.sh --path="/path/to/a folder with spaces"
我得到以下输出:
+ printf '%s\n' '--path=/path/to/a folder with spaces'
--path=/path/to/a folder with spaces
+ echo '--path=/path/to/a folder with spaces'
--path=/path/to/a folder with spaces
+ echo -e '--path=/path/to/a folder with spaces'
--path=/path/to/a folder with spaces
+ printf '%s\n' --path=/path/to/a folder with spaces
--path=/path/to/a
folder
with
spaces
+ echo --path=/path/to/a folder with spaces
--path=/path/to/a folder with spaces
+ echo -e --path=/path/to/a folder with spaces
--path=/path/to/a folder with spaces
我希望得到正确解决方案的以下输出之一:
--path=/path/to/a\ folder\ with\ spaces`
--path='/path/to/a folder with spaces'`
--path="/path/to/a folder with spaces"`
最佳答案
问题是您希望将句法引号传递给您的脚本;他们不是。所有这三个
--path=/path/to/a\ folder\ with\ spaces
--path='/path/to/a folder with spaces'
--path="/path/to/a folder with spaces"
由调用者计算,为参数产生完全相同的值(--path=/path/to/a folder with spaces
)。在您的脚本中引用位置参数会保留这些空格,但您的脚本无法知道调用它的人如何创建该值。 (它可能是以您的脚本一无所知的方式创建的;考虑像 dash -c 'printf "%s\n""$1"' _ $'\t'
这样的命令从bash
。dash
获取单个制表符作为其参数,但它对 $'...'
语法一无所知 bash
用于创建它。)
关于linux - 在 Bash(和其他 shell 语言)中,如何在通过的参数中保留空格转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55760322/