Bash Shell脚本札记(持续更新:2021-9-10)

注意:

1、编写shell脚本最好不要使用Tab制表符缩进,在被其他程序调用的场景下,可能会有问题!
2、crond定时任务执行shell脚本编写需要注意:
    2.1、如果要用到环境变量一定要加上;

if [ -f /etc/profile ];then
  . /etc/profile
fi
if [ -f ~/.bash_profile ];then
  . ~/.bash_profile
fi

    2.2、尽量不用相对路径。

awk调用系统命令

# 将新镜像tag后push
docker images |grep -i 'google_containers'|awk -F"com| *" '{args=$1"com"$2":"$3" 192.168.35.100"$2":"$3;cmd="docker tag "args";docker push 192.168.35.100"$2":"$3;system(cmd)}'

# 将某些镜像push
docker images|grep  192.168.1.1|awk '{cmd="docker push "$1":"$2;system(cmd)}'

awk ?:表达式

# Syntax:
# condition ? value_if_true : value_if_false
# git.tigerbrokers.net/libs/bingo v0.2.4-0.20210609090044-6ebc9de00776
cat go.mod | grep 'libs/bingo v'|sed 's|// indirect||g' |awk -F '-| ' '{print $1"/tools/bingoctl@"($4==""?$2:$4)}'

awk分割身份证号,输出性别(男:1,女:2)

for i in $(cat id-file);do echo $i| awk '{if (substr($1,17,1)%2==0) {print 2} else {print 1}}';done

awk求平均值

cat test1.log |awk '{sum+=$1} END {print "Average = ", sum/NR}'

awk求和

awk 'BEGIN{sum=0}{sum+=$1}END{print sum}' test1.log
cat test1.log |awk '{sum+=$1} END {print "Sum = ", sum}'

awk分割身份证号,获取出生日期

# 将所有身份证号,按照行写到id-file文件里,用下面的脚本批量获取出生日期
echo 110212198801023452 |awk '{if (substr($1,17,1)%2==0) {print 2} else {print 1}}'

for i in $(cat id-file);do echo $i| awk '{print substr($1,7,4)"/"substr($1,11,2)"/"substr($1,13,2)}';done

awk行转列

awk '{for(i=1;i<=NF;i++)print $i}'
或
awk '{ OFS="\n"; $1=$1; print $0}'  #这里的$1=$1的作用,就是为了触发根据OFS,$0进行重新构

awk去掉字符串前后空格

echo " A B C "|awk '{gsub(/^ *| *$/,"");print}'
或
echo " A B C "|awk 'gsub(/^ *| *$/,"")'
或(下面\s在centos5、6上不识别,最好还是用上面的方式。)
echo " A B C "|awk 'gsub(/^\s*|\s*$/,"")'

awk获取树形数据 

$ ipvsadm -Ln |awk '/192.168.35.12:30080/,NR==NR+1{if($0 !~ /192.168.35.12:30080/ && $0 ~ /^TCP|^UDP/)exit;print}'
TCP  192.168.35.12:30080 rr
  -> 172.254.4.6:8080             Masq    1      0          0         
  -> 172.254.4.7:8080             Masq    1      0          0         
  -> 172.254.4.8:8080             Masq    1      0          0         
  -> 172.254.5.2:8080             Masq    1      0          0         
  -> 172.254.5.3:8080             Masq    1      0          0    

awk筛选

# awk正则不支持\d,只能用[0-9],匹配有效电话号码:xxx-xxx-xxxx或(xxx) xxx-xxxx
cat file.txt |awk '/^([0-9]{3}-|\([0-9]{3}\)\s{1})[0-9]{3}-[0-9]{4}$/{print $0}'

grep筛选

# grep使用Perl的正则引擎,可以解析标准的正则表达式
# grep -E或者egrep只是简单扩展正则表达式,比如|、&这些符号,用于grep多条件查询,并非是使用标准正则# 表达式。
grep -P '^(\d{3}-|\(\d{3}\)\s{1})\d{3}-\d{4}$' file.txt

awk字符串转数组&&二进制转十进制

$ echo 100000000|awk '{for(i=1;i<length($0)+1;i++){arr[i]=substr($0,i,1)};}END{sum=0;for(i=1;i<length($0)+1;i++){sum+=arr[i]*2^(length($0)-i);}print sum}'
256

统一字符输出(避免因中英文输出结果不同,判断出错)

LANG_BAK=$LANG;LANG=C
……
LANG=$LANG_BAK
unset LANG_BAK

整数算术运算

NUMBER=`expr $NUMBER + 1`
# 或
let NUMBER=NUMBER+1

小数算术运算

# 获取当前服务器CPU空闲率
cpu_free=`iostat -c 1 2 |grep -v '^$'|tail -n 1|awk '{print $6}'`
# 计算当前服务器CPU使用率
cpu_used=$(awk 'BEGIN{print 100 - "'$cpu_free'"}')

# 如果有bc,则更简单
echo "12.312 + 12.688" |bc

变量的替换

#变量为空word替换,不赋值给变量:$i不变
i="hello world" && echo ${i:-word}
hello world
i="" && echo ${i:-word}           
word
#变量为空word替换,并赋值给变量,用于默认值设置
i="" && echo ${i:=word}
word
echo $i
word
#变量不为空word替换,不赋值给变量:$i不变
i="hello world" && echo ${i:+word}
word
echo $i
hello world
#截取变量,不赋值给变量:$i不变
${value:offset:length}
e=abcdefghijk && echo ${e:5:${#e}-5}
同
e=abcdefghijk && echo ${e:5}
fghijk
#替换变量,不赋值给变量:$i不变
i="hello world" && echo ${i/o/b}
hellb world
i="hello world" && echo ${i//o/b}
hellb wbrld

#当然,如果想改变已有变量,可以进行复制运算:
i="hello world" && i=${i//o/b}
echo $i
hellb wbrld

变量嵌套

INSTALL_PATH=$(eval echo `cat $ORACLE_USER_HOME/.bash_profile|grep "ORACLE_HOME="|awk -F= '{print $2}'`)

变量传递

变量传递:1、传递变量名;2、传递变量值;
cat >> filename <<EOF 将变量写入文件:默认变量会被解析,传递变量值,如果想要保持$variable不变,需要用\$将屏蔽转义。 
sed -i "s/LOCAL_IP/$LOCAL_ADDR/g" 
单引号下:变量不会被解析;双引号下:变量会被解析。

if 判断

# 变量为空进行逻辑判断
if [  ${telnetWrapper:-0} -ne 0 ];then
  
fi
# 字符串比较
if [ "$file_owner" == "root:root" ];then
  echo "k8s result:true"
else
  echo "k8s result:false"
fi

# 数字比较
if ([ $user_mod -le 7 ] && [ $group_mod -le 0 ] && [ $other_mod -le 0 ]);then
  echo "k8s result:true"
else
  echo "k8s result:false"
fi

# test命令进行布尔运算
#function if_func() { test $user_mod -le 7 && test $group_mod -le 0 && test $other_mod -le 0 ; }
# []下的布尔运算
function if_func() { [ $user_mod -le 7 ] && [ $group_mod -le 0 ] && [ $other_mod -le 0 ]; }
if if_func;then
  echo "k8s result:true"
else
  echo "k8s result:false"
fi

字符串正则比较

#变量TMP_ARG不以/结束,则追加
[[ ! "$1" =~ .*\/$ ]] && TMP_ARG=$TMP_ARG"/"

#变量str以he开头,则打印
[[ "$str" =~ ^he.* ]] && echo $str

获取执行脚本所在目录

script_abs=$(readlink -f "$0")
script_dir=$(dirname $script_abs)
或
script_dir=$(cd `dirname $0`; pwd)

字符串转数组

file_mod=($(stat -c %a $CONFIG_FILE |awk '{for(i=1;i<=3;i++) print substr($1,i,1)}'))

string="hello,shell,split,test" ;array=(${string//,/ })  

计算所有进程使用物理内存总和

ps -aux --no-header |awk '{sum+=$6}END{print sum/1024"MB"}'

echo -e和tput 命令

#!/bin/bash
for((i=30;i<=47;i++));do
  echo "\033[$i""m Hello World\033[0m"
  echo -e "\033[$i""m Hello World\033[0m"
done
echo -e "\033[30m\033[47m Hello World\033[0m"

for i in {0..7};do
  echo 'printf "$(tput setaf '$i') %s$(tput sgr0)\n" "Hello World"'
  printf "$(tput setaf $i) %s$(tput sgr0)\n" "Hello World"
done

for i in $(seq 0 7);do
  echo 'printf "$(tput setab '$i') %s$(tput sgr0)\n" "Hello World"'
  printf "$(tput setab $i) %s$(tput sgr0)\n" "Hello World"
done

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值