您现在的位置是:网站首页> 编程资料编程资料

shell脚本查看k8s日志介绍_linux shell_

2023-05-26 375人已围观

简介 shell脚本查看k8s日志介绍_linux shell_

查看日志:

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,因此是脚本编码的问题。

在这里插入图片描述

2.命令中的grep

在这里插入图片描述

可以发现最终拼接出来的字符串,是一条正确的命令,但是通过${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日志介绍的文章就介绍到这了,更多相关shell查看k8s日志内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

-六神源码网