1. shell脚本中常用函数
#!/bin/bash
RunLog="./run.log"
function green(){
echo -e "\033[32m$*\033[0m"
}
function red(){
echo -e "\033[31m\033[01m$*\033[0m"
}
function get_jobid(){
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