目录
  • 占位符的方式
  • 指定参数 getopts
  • 问题
    • 1.执行 shell 脚本\r问题
    • 2.命令中的grep

查看日志: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日志内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!