shell 编程 案例

说明:

  1. vim 文件名.sh 创建文件
  2. sh 文件名.sh 运行shell脚本

案例

1. 判断当前用户是否是root

#!/bin/bash

if [ ${USER} == 'root' ]
then
        echo "this is root"
else
        echo "you are not root"
fi
exit

2. 向脚本传递参数,创建用户,并在 /home目录下创建对用账户的文件夹,文件夹名为账户名。密码不输入时默认为:123456

#!/bin/bash
echo "create user start:"
read -ep " please input username: " username

if [ -z ${username} ]
then
        #username is empty
        echo "username is empty ! please input username!"
        exit 1001
fi

stty  -echo #close show echo content
read -ep " please input password: " password
stty echo #open show echo content


#while passowrd is empty , password is 123456
if [ -z ${password} ]
then
        password=123456
fi

useradd ${username}
echo ${password} | passwd --stdin ${username}

mkdir /home/${username}
echo "${username} create success !"
exit

3. 井号进度条:

#!/bin/bash
progressBar(){
        i=0
        while :
        do
                if [ ${i} -ge  100 ]
                then
                        break
                fi
                echo -n "#"
                sleep 0.2
                i=` expr ${i} + 10`

        done
        printf "\n success!"
}

progressBar &
killall $0
exit

4. 横线旋转的进度条 ,其4个状态: - \ | /

	#!/bin/bash
progressBar2(){
        i=0
        setTime=0.2
        status=0
        while :
        do
                status=`expr ${status} + 1 `
                case ${status} in
                1)
                        echo  -e '-'"\b\c"
                        sleep ${setTime}
                        ;;
                2)
                        echo  -e '\\'"\b\c"
                        sleep ${setTime}
                        ;;
                3)
                        echo  -e '|'"\b\c"
                        sleep ${setTime}
                        ;;
                4)
                        echo  -e '/'"\b\c"
                        sleep ${setTime}
                        ;;

                *)
                        status=0
                esac
                i=`expr ${i} + 5`
                if [ ${i} -gt 100 ]
                then
                        break
                fi
        done

}
progressBar2

5. 石头剪刀布游戏

#!/bin/bash
echo "the finger-guessing game"
echo "1. Rock"
echo "2. Paper"
echo "3. Scissors"
read -p "input your choose: " yourChoose

random=$[RANDOM%3 + 1]

case ${yourChoose} in
1)
        echo "you choose: Rock"
        if [ ${random} -eq ${yourChoose}  ]
        then
                echo "equals"
                echo "computer choose: Rock"
        elif [ ${random} -eq 2 ]
        then
                echo "you lose"
                echo "computer choose: Paper"
        elif [ ${random} -eq 3 ]
        then
                echo "you win"
                echo "computer choose: Scissors"
        fi
        ;;
2)
        echo "you choose: Paper"
        if [ ${random} -eq ${yourChoose}  ]
        then
                echo "equals"
                echo "computer choose: Paper"
        elif [ ${random} -eq 3 ]
        then
                echo "you lose"
                echo "computer choose: Scissors"
        elif [ ${random} -eq 1 ]
        then
                echo "you win"
                echo "computer choose: Rock"
        fi
        ;;
3)
        echo "you choose: Scissors"
        if [ ${random} -eq ${yourChoose} ]
        then
                echo "equals"
                echo "computer choose: Scissors"
        elif [ ${random} -eq  1 ]
        then
                echo "you lose"
                echo "computer choose: Rock"
        elif [ ${random}  -eq 2 ]
        then
                echo "you win"
                echo "computer choose: Paper"
        fi
        ;;

*)
        echo "input error"
        ;;
esac

6. 猜数字游戏

#!/bin/bash
echo " Guess the number  "

:<<!
 random a num that it is from 1 to 100
!
randomNumber=$((RANDOM%100+1))
less=0
more=0
isfirst=0 #first=0
echo "created the number from 1 to 100 ! success "
while :
do
        read -ep "input your number: " yourGuessNumber
        if [ ${yourGuessNumber} -eq ${randomNumber} ]
        then
                echo "you win! the random Number is "${randomNumber}
                exit
        elif [[ ${yourGuessNumber} -le 0 || ${yourGuessNumber} -gt 100 ]]
        then
                echo "please input number that it is from 1 to 100 !"
        elif [ ${yourGuessNumber} -gt ${randomNumber}  ]
        then
                echo "!!! too more! guess: ${less} to ${yourGuessNumber} "
                more=${yourGuessNumber}
                isfirst=1
        else
                if [ ${isfirst} -eq 0 ]
                then
                        echo "!!! too less! gues:${yourGuessNumber} to 100"
                        more=100
                else
                        echo "!!! too less! gues:${yourGuessNumber} to ${more}"
                fi
                isfirst=1
                less=${yourGuessNumber}
        fi
done

7. 遍历指定路径下的文件夹,统计指定格式文件夹的数量

统计 /home/ 下的所有格式为指定日期的文件夹 数量,并将结果写入countResult.txt文件中

#/bin/bash
read -ep '请输入开始时间的年月日,格式为【yyyy-MM-dd】:' ymd
if [ -z ${ymd} ]
then
        echo '未输入开始时间,退出程序'
        exit 1001
fi

read -p '请输入'${ymd}'往前指定的天数:' beforDayNum
if [ -z ${beforDayNum} ]
then
        echo '未输入'${ymd}'往前指定的天数,退出程序'
        exit 1001
fi

# 存放所有需要查询的日期
imputDate=$(date -d  "${ymd}" +%Y-%m-%d)
dayArr=()
beforDayNum_copy=${beforDayNum}
while :
do
  if [  ${beforDayNum_copy} -le -1 ]
  then
    break
  fi

  yestertday=$(date -d "${imputDate} ${beforDayNum_copy} days ago" "+%Y-%m-%d")
  # echo ${yestertday} # 2022-09-09
  dayArr[${beforDayNum_copy}]=${yestertday}
  beforDayNum_copy=`expr ${beforDayNum_copy} - 1 `
done

echo "需要统计的日期如下:"
for(( i=0;i<${#dayArr[@]};i++)) do
	#${#array[@]}获取数组长度用于循环
	echo ${dayArr[i]};
done;

read -ep "请确认【y:日期正确,n:日期有误】:" sure
if [  ${sure} == 'y' ]
then
  touch /home/countResult.txt

  carNum=0
  carNos=$(ls /home/)
  for(( i=0;i<${#dayArr[@]};i++)) do
    for carNo in ${carNos}
    do
      pathSerch="/home/"${carNo}"/"${dayArr[i]:0:4}"/"${dayArr[i]:5:2}"/"${dayArr[i]:8:2}
      if [ -d ${pathSerch} ]
      then
        carNum=`expr ${carNum} + 1`
      fi
    done
    echo ${dayArr[i]}"存在文件夹总数为:"${carNum} >> /home/counResult.txt
    carNum=0
  done;

  cat /home/countResult.txt
else
  echo "确认日期有误,退出程序"
  exit 1001
fi

8. 批量启动或停止jar包的运行

运行多个 java的jar包,结合linux 的定时任务,定时运行jar包和关闭jar包。
创建shell脚本文件名称为:runJar.sh

#!/bin/bash
# 脚本执行日志文件存放地址,自定义
logPath="jarStartAndStop.log"
# 在2023年7月3日至7月7日 期间,每天早上6:00开启接口,每天下午18:00点关闭接口
# jar包名称
# 声明关联数组对象,存放jar包数据
declare -A jarArr
# key 为 jar包名称
# value 为jar 包路径
jarArr["ShellTestDemo-0.0.1-SNAPSHOT_2.jar"]="/home/tempJar/20230627/ShellTestDemo-0.0.1-SNAPSHOT_2.jar"
jarArr["ShellTestDemo-0.0.1-SNAPSHOT.jar"]="/home/tempJar/20230627/ShellTestDemo-0.0.1-SNAPSHOT.jar"


# 脚本可用时间段
startTime="2023-06-02 23:59:59"
endTime="2023-07-07 23:59:59"

# jar包打开的时间段.分别为 早上6点 和下午18点之间是打开的
openStart=6
openEnd=18

# jar包开关时间点判断
onHour() {
	startHour=$(date +"%H")
	if [ "$startHour" -ge "$openStart"  ]  && [ "$startHour" -lt "$openEnd" ]; then
		# echo  "当前时间在 6:00 至 18:00 之间"
		echo 1
	else
		# echo "当前时间不在 6:00 至 18:00 之间"
		echo 0
	fi 
}

# 判断jar包是否运行中 
jarIsRun() {
	local jarName=$1
	
	isRun=$(ps -ef | grep -c "$jarName")
	if [ "$isRun" -gt 1 ]; then
		# jar 包正在运行
		echo 1
	else
		# jar 包未运行
		echo 0
	fi
}

# 循环遍历jar包数组,key 为jar包名称,value为jar包地址
for key in "${!jarArr[@]}"; do
	nowTime=$(date +"%Y-%m-%d %H:%M:%S")
	echo "当前时间:$nowTime" >> "$logPath"
	if [[ "$nowTime" > "$startTime" && "$nowTime" < "$endTime" ]];  then
		echo "【 $nowTime -- $LINENO 】在指定执行的时间段:$startTime$endTime 之间" >> "$logPath"
		echo "【 $nowTime -- $LINENO 】脚本开始执行....." >> "$logPath"
		
		jarName="$key"
		jarPath="${jarArr[$key]}"
		echo "【 $nowTime -- $LINENO 】脚本开始处理jar包: $jarName  " >> "$logPath"
		echo "【 $nowTime -- $LINENO 】jar包路径:$jarPath" >> "$logPath"
	
		jarIsRun=$(jarIsRun "$jarName")
		echo "【 $nowTime -- $LINENO 】jar 包$jarPath 的运行状态为【0.未运行;1.运行中】:$jarIsRun " >> "$logPath"
		isOnHour=$(onHour)
		if [ "$isOnHour" == 1 ]; then
			echo  "【 $nowTime -- $LINENO 】当前时间在 6:00 至 18:00 之间" >> "$logPath"
			if [ "$jarIsRun" == 0 ]; then
				echo  "【 $nowTime -- $LINENO 】jar包未运行,开始运行jar包:$jarPath" >> "$logPath"
				java -jar "$jarPath" >/dev/null &
			fi
		else
			echo "【 $nowTime -- $LINENO 】当前时间不在 6:00 至 18:00 之间" >> "$logPath"
			if [ "$jarIsRun" == 1 ]; then
				echo  "【 $nowTime -- $LINENO 】jar包运行中,停止运行jar包:$jarName" >> "$logPath"
				kill -9 $(ps -ef | grep "$jarName" | awk '{print $2}')
			fi
		fi
		echo "【 $nowTime -- $LINENO 】脚本执行结束....." >> "$logPath"
		echo " "
		echo " "
	else
		echo "【 $nowTime -- $LINENO 】不在指定执行的时间段:$startTime$endTime 之间,退出脚本执行。" >> "$logPath"
		exit 1001
	fi
done
tail -500f "$logPath"

定时执行脚本配置,root运行以下命令进入定时任务配置

crontab -e

在编辑窗口编写定时表达式。例如:每一个小时执行一次脚本

  0  */1  *  *  *  sh runJar.sh
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Shell脚本高级编程教程,希望对你有所帮助。 Example 10-23. Using continue N in an actual task: 1 # Albert Reiner gives an example of how to use "continue N": 2 # --------------------------------------------------------- 3 4 # Suppose I have a large number of jobs that need to be run, with 5 #+ any data that is to be treated in files of a given name pattern in a 6 #+ directory. There are several machines that access this directory, and 7 #+ I want to distribute the work over these different boxen. Then I 8 #+ usually nohup something like the following on every box: 9 10 while true 11 do 12 for n in .iso.* 13 do 14 [ "$n" = ".iso.opts" ] && continue 15 beta=${n#.iso.} 16 [ -r .Iso.$beta ] && continue 17 [ -r .lock.$beta ] && sleep 10 && continue 18 lockfile -r0 .lock.$beta || continue 19 echo -n "$beta: " `date` 20 run-isotherm $beta 21 date 22 ls -alF .Iso.$beta 23 [ -r .Iso.$beta ] && rm -f .lock.$beta 24 continue 2 25 done 26 break 27 done 28 29 # The details, in particular the sleep N, are particular to my 30 #+ application, but the general pattern is: 31 32 while true 33 do 34 for job in {pattern} 35 do 36 {job already done or running} && continue 37 {mark job as running, do job, mark job as done} 38 continue 2 39 done 40 break # Or something like `sleep 600' to avoid termination. 41 done 42 43 # This way the script will stop only when there are no more jobs to do 44 #+ (including jobs that were added during runtime). Through the use 45 #+ of appropriate lockfiles it can be run on several machines 46 #+ concurrently without duplication of calculations [which run a couple 47 #+ of hours in my case, so I really want to avoid this]. Also, as search 48 #+ always starts again from the beginning, one can encode priorities in 49 #+ the file names. Of course, one could also do this without `continue 2', 50 #+ but then one would have to actually check whether or not some job 51 #+ was done (so that we should immediately look for the next job) or not 52 #+ (in which case we terminate or sleep for a long time before checking 53 #+ for a new job).
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小张帅三代

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值