写shell脚本过程中的一些总结

1. shell脚本中常用函数

#!/bin/bash
###########################################
#Name :****
#Author :****
#Description :*******
#Created time :**********
###########################################
## 绿色输出
RunLog="./run.log"
function green(){
	echo -e "\033[32m$*\033[0m"
}

## 红色输出
function red(){
	echo -e "\033[31m\033[01m$*\033[0m"
}

## 可以模拟生成id,可用于随机数,脚本编号

function get_jobid(){
	#echo $(printf "%08d\n" $(expr $(date "+%s") - 1581077100 ))
	echo $(printf "%08d\n" $(expr $(date "+%s") - 1581077100 ))
}

## 用于信息打印,格式化输出
function log_info(){
	echo -e "[$(date "+%F %T")] [INFO] [${JobID}] [$0] $*" | tee -a ${RunLog}
}

## 用于错误信息打印
function log_error(){
	RetCode=$1
	shift
	RetMsg=$*
	echo -e "[$(date "+%F %T")] [ERROR] [${JobID}] [$0] ${RetMsg} RetCode=${RetCode}" | tee -a ${RunLog}
}

## 用于警告信息打印
function log_warning(){
	RetCode=$1
	shift
	RetMsg=$*
	echo -e "[$(date "+%F %T")] [WARN] [${JobID}] [$0] ${RetMsg} RetCode=${RetCode}" | tee -a ${RunLog}
}

## 检查目录是否存在或者是否有访问权限
function check_directory(){
	directory=$1
	if [ ! -d ${directory} ];then
		log_error 1 "目录检查${directory}失败。请检查目录是否存在,或者是否具有访问权限"
	fi
}

## 检查文件是否存在或者是否有访问权限
function check_file(){
	file=$1
	if [ ! -f ${file} ];then
		log_error 1 "文件检查${file}失败。请检查目录是否存在,或者是否具有访问权限"
	fi
}

## 获取参数目录列表
function get_dir_list(){
	directory=$1
	check_directory ${directory}
	ls -l ${directory} | grep ^d | awk '{print $NF}'
}
## 

2. 指定hostfile.txt文件后,要求获取所有host节点的总CPUs数

执行脚本的host节点与hostfile文件中的节点均可免密登入
hostfile.txt
hostname1
hostname2
hostname3
hostname4
#!/bin/bash
all_cpus=0
while read host
do
	temporary=$(ssh root@{host} "lscpu | grep ^CPU\(s\)" > ./test.txt < /dev/null)
	cpus=`cat ./test.txt | awk '{print $NF}'`
	all_cpus=$((${all_cpus} + ${cpus}))
done < hostfile.txt
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值