HP-UX KSH 脚本 - 使用 $@ 传递空白参数



我在 HP-UX KSH 中开发的脚本有一个"问题"。该脚本包含许多函数,我需要在它们之间传递同一组参数。一切都很好,但有些参数可能是空白的。使用双双引号 ("( 传递空白参数很容易,但是如果我想使用 ${@} 将一组完整的参数从一个函数传递到另一个函数,包括空格怎么办?为了使事情变得棘手,每次都可以有可变数量的参数,因此该方法必须是动态的。

示例:我有一个名为 test1 的函数,它接受许多参数。它们中的任何一个都可以为空。我还创建了一个名为 test2 的函数,其中传递了 test1 的所有参数:

test1()
{
echo 1-1: ${1}
echo 1-2: ${2}
test2 ${@}
}
test2()
{
echo 2-1: ${1}
echo 2-2: ${2}
}
# test1 "" hello
1-1:
1-2: hello
2-1: hello
2-2:

问题是,如果 ${1} 为空,则 test1 中的 ${2} 在 test2 中显示为 ${1}。因此,为了解决这个问题,我创建了这段代码,它有效地创建了一个函数字符串,所有参数都用双引号括起来:

test1()
{
typeset var FUNC="test2"
typeset -i var COUNT=1
echo 1-1: ${1}
echo 1-2: ${2}
while [ ${COUNT} -le ${#@} ]; do
typeset var PARAM=$(eval "echo $${COUNT}")
FUNC="${FUNC} "${PARAM}""
((COUNT=COUNT+1))
done
eval "${FUNC}"
}
# test1 "" hello
1-1:
1-2: hello
2-1: 
2-2: hello

这很好用,谢谢。现在谈谈我的"问题"。

实际上是否可以将上述代码封装在自己的函数中?对我来说,这似乎是一个陷阱 22,因为您必须运行该代码才能传递空白参数。我必须在脚本中多次重复此代码片段,因为我找不到其他方法。有吗?

任何帮助或指导将不胜感激。

以下是我编写函数的方式:

show_params() {
typeset funcname=$1
typeset -i n=0
shift
for arg; do 
((n++))
printf "%s:%d >%s<n" "$funcname" $n "$arg"
done
}
test1() { show_params "${.sh.fun}" "$@"; test2 "$@"; }
test2() { show_params "${.sh.fun}" "$@"; }
test1 "" 'a string "with double quotes" in it'
test1:1 ><
test1:2 >a string "with double quotes" in it<
test2:1 ><
test2:2 >a string "with double quotes" in it<

使用您对test1的定义,它构建了一个包含命令的字符串,在所有参数周围添加双引号,然后对字符串进行评估,我得到这个结果

$ test1 "" 'a string "with double quotes" in it'
1-1:
1-2: a string "with double quotes" in it
test2:1 ><
test2:2 >a string with<
test2:3 >double<
test2:4 >quotes in it<

那是因为你正在这样做:

eval "test2 "" "a string "with double quotes" in it""
# ......... A A  A          B                   B       A
# A = injected quotes
# B = pre-existing quotes contained in the parameter

最新更新