在 bash 脚本中,我们可以使用 转义空格\ 。有什么方法可以从代码中执行相同的操作吗?
$ a=hello\ world
$ echo $a
hello world
$ b=${a:?} # ? used as dummy; it will not work
$ echo $b
hello\ world
Run Code Online (Sandbox Code Playgroud)
来电者.bash
#!/bin/bash
name=$1
if [[ -n $name ]]; then
where_query="--where name $name"
fi
mycommand $where_query
Run Code Online (Sandbox Code Playgroud)
mycommand是外部程序,我们无法修改。添加虚拟代码仅用于说明目的。
#!/bin/bash
for i in "${@}"
do
echo "$i"
done
Run Code Online (Sandbox Code Playgroud)
实际的
$ caller.bash "foo bar"
--where
name
foo
bar
Run Code Online (Sandbox Code Playgroud)
预期的
$ caller.bash "foo bar"
--where
name
foo bar
Run Code Online (Sandbox Code Playgroud)
Fed*_*eli 10
对于简单的字符串变量,您想要做的事情是不可能的。您试图将三个参数传递给“外部程序” mycommand ,或者不传递任何参数。您应该使用 bash 数组。请尝试以下操作:
来电者.bash:
#!/bin/bash
name=$1
if [[ -n $name ]]; then
where_query=("--where" "name" "$name")
fi
mycommand "${where_query[@]}"
Run Code Online (Sandbox Code Playgroud)
您的脚本也存在引用错误。在尝试使用它们之前,您应该在https://www.shellcheck.net/上检查所有脚本。
| 归档时间: |
|
| 查看次数: |
12990 次 |
| 最近记录: |