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

HP-UX KSH scripting - passing blank parameters with $@

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

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

test1()
{
  echo 1-1: 
  echo 1-2: 

  test2 ${@}
}

test2()
{
  echo 2-1: 
  echo 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: 
  echo 1-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

这很好用,谢谢。现在到我的 'problem'.

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

如有任何帮助或指导,我们将不胜感激。

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

show_params() {
    typeset funcname=
    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