shell (eleven) the while loop

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/wzj_110/article/details/100514903

A while loop scenarios

little while loop used at work, usually daemon program or always loop execution scene, the other loop calculation will use for replacement while

Two types while loop

When the type (while) and till (until) type loop statement

1, while conditional sentence

while 条件

      do

      指令 …

done

# 先判断条件(满足)--->执行--->判断条件--->...

2, until conditionals

# 不常用

until 条件

      do

      指令 ...
done

# 先判断条件(不满足)--->执行--->判断条件--->...

Three related commands

sleep and usleep

sleep : 执行挂起指定的秒数

usleep:功能把进程挂起一段时间, 单位是微秒 #1000000us

# 说明:如果是分钟级别的则用--> 定时任务

Three practice

(1) every two seconds the load of the printing system

#!/bin/bash
while true
do
        uptime      # 核心命令
        sleep  2    # 两秒打印一次
done

# 可用 ctrl+c取消

# 说明: while true 表示条件永远为真,因此为死循环会一直执行,也即守护进程!

(2) the script running in the background

#!/bin/bash
while true
do
        uptime  >> /mnt/log
        sleep 2
done

# 执行:后台运行

sh while2.sh &

# 检测

tail -f /mnt/log

# 说明:即使把窗口关闭还是会运行

# 执行脚本,跟数据库相关的,插入数据等,一定不要命令行输出,放到后台执行

# 客户端突然端了怎么办,执行到哪了

Related : Prevents script execution client terminal

# 防止客户端执行脚本中断的方法。

1、sh while.sh &                 # 通过kill -p pid 关闭

2、nohup while.sh &

# 说明:上述是开发人员常用的

3、screen保持回话 # 比较高级

screen command

Memories : Related Extensions script executed in the background

ctl+c:停止执行当前脚本或任务

ctrl+z:暂停执行当前脚本或任务

bg:把当前脚本(前台)或任务放入后台执行

fg:当前脚本或任务进行前台执行,如果有多个任务,可以fg加任务编号调出

jobs:查看当前执行的脚本或任务 

Process management command

# 进程管理常用16个命令

bg:后台运行

fg:挂起程序

jobs:显示后台程序

kill、killall、pkill:杀掉进程

crontab:设置定时

ps:查看进程

pstree:显示进程状态树

top:显示进程

nice:改变优先权

nohup:用户退出系统之后继续工作

pgrep:查找匹配条件的进程

strace:跟踪一个进程的系统调用情况(strace + pid)

ltrace:跟踪进程调用库函数的情况

vmstat:报告虚拟内存统计信息 

Demand 2 : 1 to 100 and realize the while the

#!/bin/bash
i=1;sum=0
while [ $i -le 100 ]
  do
    ((sum+=$i))
    ((i++))
  done
echo $sum 

# 方法很多-->这里以一种炫技的方式进行

Said shell in a variety of symbols

Description: shell itself is not suitable for calculation of efficiency!

Note : more use of sophisticated algorithms, more efficient code execution!

Demand 3 : Use a while loop vertical print 10,9,8 ...

#!/bin/bash
i=10
while [ $i -gt 0 ]
  do
    echo "$i"
    ((--i))
  done

# 注意:与之前的做对比!

Supplementary: vim script generation

NAT-related

Demand 4 : mobile phone recharge 10 yuan each send one SMS cost 0.15 yuan, 0.15 yuan less than the current balance can not send text messages, inadequate tips the balance, please recharge, you can send text messages after the user is allowed to continue to recharge

#!/bin/bash
# 1元是100分
# 余额的初始化
total=0
# 提示-->选项
menu='
1:充值
2:发送信息
3:退出
'
# 充值
pay(){
  read -t 10 -p "Pls input pay money:" num
  # 输入的不是整数
  expr ${num} + 1 &>/dev/null
  [ $? -ne 0 ]&&{
    echo "Input error"
    return 1
  }
  # 输入的合法的整数
  if [ ${num} -gt 0 ];then
    # 变量都是全局的,可以在其它地方引用!
    total=$(( $total + $num * 100 ))
  else
    echo "Input error"
    return 1
  fi
}
 
# 发短信

send(){
  if [ ${total} -gt 15 ];then    # 是不是余额小于0.15元
    echo "send messages is ok."
    total=$(( $total - 15 ))
  else
    echo "余额不足!"
  fi
}
 
while true
do
  echo "当前余额:${total}"
  echo ${menu}
  read -t 10 -p "Pls input a num:" choice   # 与前面的menu对应
  case ${choice} in
    1) pay        # 冲值后不退出,用while循环!
    ;;
    2) send
    ;;
    3) exit 0     # 结束充值
    ;;
    *)
  esac
done 

# 说明:主要的和i锻炼shell的逻辑!

Shell small number calculated in two ways

Demand 5 : Press the while line read files way

# 方式一

    exec <FILE
    sum=0
    while read line
    do
      cmd
    done

# 方式二

    cat ${FILE_PATH} | while read line
    do
      cmd
    done

# 方式三

    while read line
    do
      cmd
    done<FILE

6 needs the total number of bytes apache access log day all of the elements in the rows:

    #/bin/bash
    exec access.log                       # 读取日志
    while read line                  
    do
      i=`echo $line|awk '{print $10}'     # 获取内容`
      expr $i + 1 &>/dev/null             # 判断是不是整数
      if [ $? -ne 0 ];then
        continue
      fi
      ((sum+=i))
    done
    [ -n "$sum" ] && echo $sum            # 最终存在内容则打印

Demand 7 : read a file, inserted upside down into a new file, empty the original file

#!/bin/bash
file=/root/read.sh
num=`wc -l ${file}|awk -F ' ' '{print $1}'`
while [ ${num} -gt 0 ]
do
  line=`tail -1 ${file}`                       # 文件倒数一行的内容
  echo ${line}
  echo ${line}>>/root/read_bak.sh
  sed -i '$d' ${file}                          # 把读入此行的内容删除
  num=`wc -l ${file}|awk -F ' ' '{print $1}'`  # 下一行内容的写入
done 

Follow-up : string immediately

Three while loop Summary

1, while circulation specialty is the execution daemon, and we do not want to quit cycling scene performed continuously for one minute cycle of treatment with a frequency less than the other while loop can be recycled almost substitute for.

2, almost all the case statements can be replaced with an if statement, the general rule passed in a small amount of fixed strings in the system startup script, with case statements, other ordinary determine if multi-purpose

3, if the work and for the most commonly used, followed by while (daemon) and case (service startup script)

Guess you like

Origin blog.csdn.net/wzj_110/article/details/100514903