shell 预热
shell 中变量用 $ 区别
在shell脚本中变量赋值等号前后不能有空格,有空格会被认为是命令
str='测试'
echo $str
arr=('test1' 'test2' 'test3') # 数组, 每个元素间以空格隔开
echo ${arr[0]} # 数组的访问
echo ${#arr[@]} # 数组长度
shell 中的 for 循环和 if
for i in $(seq 1 10)
do
if [ $i -gt 5];then # if 表达式注意空格
echo $i
fi #if 结束语
done #for 结束语
shell 中的函数
test(){
if [ $1 -eq 1 ];then # $1为第一个参数,$2为第二个,其他参数依次类推
echo 第一个参数值为$1
return 1
fi
return 0 # return 只能返回 0-255 的整数
}
test 1 # 函数调用,0为传入的第一个参数
res=$? # $?接收函数的返回值
echo res
shell 脚本判断多个进程是否存在,如不存在则重启进程
# !/bin/bash
cd ~
proc_names=(‘proc_name1’ ‘proc_name1’ ‘proc_name1’)
proc_is_run () {
proc_pid=`ps -ef | grep $1 | grep -v grep | awk '{print $2}'`
if [ -z '$proc_pid' ];then #
echo "$1进程已结束"
return 0
else
echo "$1进程已存在,pid: $proc_pid"
return 1
fi
}
for i in seq(0 $((${#proc_names[@]}-1))) # $((表达式)) 把字符串转为数字
do
proc_is_run ${proc_names[$i]}
pid_=$?
if [ $pid_ -eq 0 ]; then
{
sleep 3
echo '重启 ${proc_names[$i]} 进程'
# >>: 表示以追加的形式写入日志文件, > :以覆盖形式写入
python 脚本名 >> logs/脚本名 .log
} &
fi
done
wait
# for 循环中使用 { 命令 } & 和 wait 实现多线程运行多条命令,对多个进程进行判断, 如不使用只能等前一个进程结束以后才能对下一个进程进行判断
# 命令1 & 命令 2 执行多条命令
脚本编写完成后存为 test.sh, 存放在 ~目录下
shell 脚本编写完成后运行
cd ~
sh test.sh # 运行脚本
# 使用crontab 实现定时自动执行脚本
crontab -e
* 2 * * * sh ./test.sh #每隔两个小时执行一次脚本