unix - 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
推荐阅读
- javascript - event.currentTarget.value 返回欠精细的 javascript
- angularjs - Angular JS - http.get 忽略证书
- unity3d - 放置对象的 Unity 按钮
- javascript - 来自 JavaScript 中 JSON 的 Protobuf 消息
- mysql - Gitlab Ci Pipeline 问题:Nodejs 无法连接到 Mysql 数据库
- regex - 正则表达式查找与特定模式匹配的行
- python - 如何改善此功能的 scipy 最小化结果?
- c - STM32 UART传输问题(阻塞和中断模式)
- javascript - 如何重用代码并使其更灵活?
- reactjs - 如何在两个设定日期之间使用 Material UI “进度指示器”?