shell脚本查看k8s日志介绍

来自:网络
时间:2022-01-06
阅读:
目录

查看日志:kubectl logs -f podName --tail 100

比如我们如果想查指定的pod,指定行数,指定的内容,
每次都需要输入kubectl logs -f xxx --tail yyy | grep zzz
为了方便,可自定义脚本,输入sh .sh xxx yyy zzz即可,并且xxx支持RE;

占位符的方式

#!/bin/bash
# kubectl get pods
#notification
x="kubectl logs -f"
y="--tail"
g="|grep"
name=`kubectl get pods | grep ^$1 | awk '{print $1}'`
x="eval $x $name $y $2 $g $3"
${x}

# sh log.sh podName 20 content
# 最终:kubectl logs -f podName --tail 20 | grep content

指定参数 getopts

#!/bin/bash
# ":":如果某个选项(option)后面出现了冒号(":"),则表示这个选项后面可以接参数
x="kubectl logs -f"
y="--tail"
g="|grep"
while getopts ":n:f:c:" opt
do
    case $opt in
        n)
		name=`kubectl get pods | grep ^$OPTARG | awk '{print $1}'`
		x="$x $name"
        ;;
        f)
		x="$x $y $OPTARG"
        ;;
        c) 
        x="$x $g $OPTARG"
        ;;
        ?)
        echo "未知参数"
        exit 1;;
    esac
done
x="eval $x"
${x}
# sh log.sh -n podName -f 20 -c content
# 最终:kubectl logs -f podName --tail 20 | grep content

问题

1.执行 shell 脚本\r问题

脚本是在window下编辑完成后上传到linux上执行的,win下的换行是回车符+换行符,也就是\r\n,而unix下是换行符\n。linux下不识别\r为回车符,所以导致每行的配置都多了个\r,因此是脚本编码的问题。

shell脚本查看k8s日志介绍

2.命令中的grep

shell脚本查看k8s日志介绍

可以发现最终拼接出来的字符串,是一条正确的命令,但是通过${CMD}执行该变量报错。

原因:
如果在shell中定义一个命令,带了管道,例如

CMD=“ls -l | grep xx”

直接执行$CMD,会出现如下报错

ls: cannot access |: No such file or directory

ls: cannot access grep: No such file or directory

管道符会被解释为普通字符

加上eval

CMD=“eval ls -l | grep xx”

shell脚本查看k8s日志介绍

返回顶部
顶部