-
一、遇到问题现象描述:
为什么kubernetes项目中shell脚本文件中能通过::符号定义函数名称?
例如: hack/lib/logging.sh 中 kube::log::status()的定义:
# Print a status line. Formatted to show up in a stream of output.
kube::log::status() {
local V="${V:-0}"
if (( KUBE_VERBOSE < V )); then
return
fi
timestamp=$(date +"[%m%d %H:%M:%S]")
echo "+++ ${timestamp} ${1}"
shift
for message; do
echo " ${message}"
done
}
message 在这个脚本中是一个特殊的变量名,它在函数中被用作循环的迭代变量,用于逐个处理所有传递给函数的额外参数。这些参数在函数调用时被 shift 命令移除第一个参数后剩余的部分。
具体来说,for message; do ... done 这个循环会遍历所有传递给 kube::log::status 函数的额外参数,并将每个参数的值赋给 message 变量,然后执行循环体内的代码。在这个例子中,循环体内的代码是 echo " ${message}",它将每个消息前加上四个空格的缩进,然后打印出来。
所以,message 的作用是作为一个占位符,代表函数调用时除了第一个参数之外的所有后续参数,这些参数在函数内部被当作日志消息的一部分逐条输出。
-
二、问题相关代码片 运行结果 报错内容
[root@localhost ~]# cat t.sh
#!/usr/bin/env bash
KUBE_VERBOSE="${KUBE_VERBOSE:-2}"
kube::log::status() {
local V="${V:-0}"
if (( KUBE_VERBOSE < V )); then
return
fi
timestamp=$(date +"[%m%d %H:%M:%S]")
echo "+++ ${timestamp} ${1}"
shift
for message; do
echo " ${message}"
done
}
kube::log::status "Waiting on tarballs"
kube::log::status "Waiting on tarballs" "aa" "bb" "cc"
[root@localhost ~]# sh t.sh
t.sh:行17: `kube::log::status': 不是有效的标识符
将t.sh脚本中的::改为_ 确能正常运行
[root@localhost ~]# cat t.sh
#!/usr/bin/env bash
KUBE_VERBOSE="${KUBE_VERBOSE:-2}"
kube_log_status() {
local V="${V:-0}"
if (( KUBE_VERBOSE < V )); then
return
fi
timestamp=$(date +"[%m%d %H:%M:%S]")
echo "+++ ${timestamp} ${1}"
shift
for message; do
echo " ${message}"
done
}
kube_log_status "Waiting on tarballs"
kube_log_status "Waiting on tarballs" "aa" "bb" "cc"
[root@localhost ~]# sh t.sh
+++ [0715 16:21:28] Waiting on tarballs
+++ [0715 16:21:28] Waiting on tarballs
aa
bb
cc
-
三、我的初步解答思路
征求网友的解答:
感谢朱老师提供的参考链接:https://google.github.io/styleguide/shellguide.html#naming-conventions
这段话是关于google shell编程中命名约定的函数命名规范的说明,其中提到了如果函数是包的一部分,包名和函数名之间用双冒号分隔;还提到了对于设计为交互式使用的函数,可以选择避免使用冒号,因为这可能会干扰bash的自动补全功能。
故改用./t.sh方式运行,验证能正常运行
[root@localhost ~]# cat t.sh
#!/usr/bin/env bash
KUBE_VERBOSE="${KUBE_VERBOSE:-2}"
kube::log::status() {
local V="${V:-0}"
if (( KUBE_VERBOSE < V )); then
return
fi
timestamp=$(date +"[%m%d %H:%M:%S]")
echo "+++ ${timestamp} ${1}"
shift
for message; do
echo " ${message}"
done
}
kube::log::status "Waiting on tarballs"
kube::log::status "Waiting on tarballs" "aa" "bb" "cc"
[root@localhost ~]# sh t.sh
t.sh: line 17: `kube::log::status': not a valid identifier
[root@localhost ~]# ./t.sh
-bash: ./t.sh: Permission denied
[root@localhost ~]# chmod +x t.sh
[root@localhost ~]# ./t.sh
+++ [1106 09:37:54] Waiting on tarballs
+++ [1106 09:37:54] Waiting on tarballs
aa
bb
cc
[root@localhost ~]#
-
四、操作系统,软件版本等相关信息
centos7/8
龙蜥8