如果我在终端中输入以下带有 2 个参数的命令,则可以满足我的需要:
mycommand 'string that includes many spaces and double quotes' 'another string that includes many spaces and double quotes'
现在我将上面的内容移至 bash 脚本中。
C=mycommand 'string that includes many spaces and double quotes'
function f {
$C $1
}
# let's call it
f 'another string that includes many spaces and double quotes'
显然,这不会产生相同的结果,或任何有用的结果。但我无法想出保留和/或正确转义引号、空格以及保留实际参数数量的正确方法我的命令视为 2。
我在 Mac 上使用 GNU bash 版本 3.2.57。
答案1
如果您引用每个参数,它将作为位置参数正确处理:
#!/usr/local/bin/bash
f() {
echo "function was called with $# parameters:"
while ! [[ -z $1 ]]; do
echo " '$1'"
shift
done
}
f "param 1" "param 2" "a third parameter"
$ ./459461.sh
function was called with 3 parameters:
'param 1'
'param 2'
'a third parameter'
但请注意,包含(即最外面的)引号是不是参数本身的一部分。让我们尝试稍微不同的函数调用:
$ tail -n1 459461.sh
f "them's fightin' words" '"Holy moly," I shouted.'
$ ./459461.sh
function was called with 2 parameters:
'them's fightin' words'
'"Holy moly," I shouted.'
请注意,'
输出中复制的参数周围的 s 来自echo
函数中的语句,而不是参数本身。
为了使您的示例代码更加具有引号意识,我们可以这样做:
C=mycommand
f() {
$C "unchanging first parameter" "$1"
}
# let's call it
f 'another string that includes many spaces and double quotes'
或这个:
C=mycommand
f() {
$C "$1" "$2"
}
# let's call it
f 'Some string with "quotes" that are scary' 'some other "long" string'