zwd 发表于 2018-8-27 10:33:06

Linux Shell循环控制符与函数

  循环控制符与函数详解
  break循环控制符;continue循环控制符.
  循环控制符
  退出整个循环 则可以使用break循环控制符;
  退出本次循环后执行后续的循环,使用continue循环控制符;
  #!/bin/bash
  while true
  do
  echo "please enter a operation {1copy| 2delete|3backup|4exit }"
  read -p " please enter youroperation:" op
  case $op in
  1)
  continue
  echo " copy "
  ;;
  2)
  echo "delete"
  ;;
  3)
  echo "backup"
  ;;
  4)
  echo "exit"
  ;;
  *)
  echo " error ,try enter { 1 | 2 |3 |4 }again"
  esac
  done
  函数详解
  1-2-1-函数的定义基本知识
  1-2-2-函数的调用
  函数的定义基本知识
  如果遇到很长的路径 做个变量就行
  遇到很多重复的操作,做个函数即可
  函数的基本格式:
  name ( )
  {
  command1
  command2
  …
  }
  nginx ( )
  {
  netstat -anlpt | grep nginx
  }
  标题是函数的名称,函数体是函数内的命令集合,在编写脚本时要注意标题的唯一
  不唯一脚本的执行时则会产生错误
  函数不允许出现空命令-函数体中的命令集合必须包含至少一条命令
  定义一个函数:
  #!/bin/bash
  student()                                                               #定义函数
  {
  echo "Hello shell!"                                 #函数中的命令
  }
  echo "Now going to run student()"
  student
  echo "end the student()"
  效果:
  # sh for1.sh
  Now going to run student()
  Hello shell!                                                   #函数的执行结果
  end the student()
  注释:
  在hanshu.sh中定义了一个简单的函数
  首先执行echo “开始执行函数student”
  执行student函数
  最后执行echo”函数student执行结束”
  函数与脚本一样都是依次执行
  student(){ à名为student的函数} 代表结束
  参数的引用即传递
  环境:
  创建a.txt
  # touch a.txt
  编写脚本:
  vim yinyong.sh
  #!/bin/bash
  delete()
  {
  rm-rf $1
  mkdir$2
  }
  delete /root/shell/aa.txt /root/shell/mydir
  执行
  # sh yinyoug.sh
  # ls -ld mydir/
  drwxr-xr-x. 2 root root 6 Sep5 21:53 mydir/
  调用其他模块的函数
  source 调用其他脚本的函数
  定义一个有不同功能的模块
  # cat option.sh
  #!/bin/bash
  delete()
  {
  rm-rf $del
  }
  copy()
  {
  cp-fr $sdir $tdir
  }
  backup()
  {
  tarzcvf $tar_name $star_dir &> /dev/null
  }
  quit()
  {
  exit
  }
  再次编辑一个文件
  #!/bin/bash
  source /root/shell/option.sh
  while true
  do
  cat
页: [1]
查看完整版本: Linux Shell循环控制符与函数