【问题标题】:HP-UX KSH scripting - passing blank parameters with $@HP-UX KSH 脚本 - 使用 $@ 传递空白参数
【发布时间】:2018-11-10 20:29:49
【问题描述】:

我在 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,因为您必须运行该代码才能传递空白参数。我必须在我的脚本中多次重复这段代码 sn-p 因为我找不到其他方法。有吗?

我们将不胜感激地收到任何帮助或指导。

【问题讨论】:

标签: unix ksh hp-ux


【解决方案1】:

我会这样写你的函数:

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

【讨论】:

  • 感谢您的所有意见。非常感谢。
猜你喜欢
  • 2012-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
  • 2015-03-28
  • 1970-01-01
相关资源
最近更新 更多