ssplyh 发表于 2018-8-25 07:47:53

Shell脚本编写

  1.shell脚本就是一些命令的集合。把需要执行的一组命令记录到文档中,再去调用这个文档。
  139邮箱,收到邮件同时受到短信通知。
  shell脚步编写建议:自定义脚本放到/usr/local/sbin目录下
  2.第一个shell脚本
  vim firstshell.sh
  #! /bin/bash
  ##this is my first shell script
  ##writen by jason 2015-07-02
  date
  echo "Hello world !"
  #! /bin/bash,开头第一行,表示该文件使用bash语法
  .sh后缀,习惯
  #后面跟的注释,良好习惯,便于以后查看脚步
  执行脚本:sh firstshell.sh 或者 ./firstshell.sh(有时缺少权限时,chmod修改)
  3.脚本中变量的使用
  vi variable.sh
  #! /bin/bash
  ## In thie shell script we will use variables
  ## writen by jason 2015-07-02
  d=`date +%H:%M:%S`
  echo "This script begin at $d"
  echo "Now we will sleep 2 seconds."
  sleep 2
  d1=`date +%H:%M:%S`
  echo "This script end at $d1"
  变量d和d1的定义时,使用反引号` `,变量内容使用到其他命令的结果(shell脚步基础知识博客中)。
  脚本总引用变量,需加上$
  3.1 数值运算,两个数的和 sum
  vi sum.sh
  #! /bin/bash
  ## Sum of tow numbers
  ## By jason 20150702
  a=1
  b=2
  sum=$[$a+$b]
  echo $sum
  数学计算,要用[ ]括起来,并且最外面要加一个 $
  3.2用户交互,用户输入
  vi read.sh
  #! /bin/bash
  ## Use "read" in shell script
  ## By jason 20150702
  read -p "Please input a number:" x
  read -p "Please input anoter number" y
  sum=$[$x+$y]
  echo "The sum of two number is : $sum"
  read就是用在和和用户交互,把用户输入的字符串作为变量值
  -x 查看shell执行的过程,sh -x read.sh
  3.3 shell预设变量 $1,$2,$0(打印脚本本身的名字)
  vi option.sh
  #! /bin/bash
  ##
  ##
  sum=$[$1+$2]
  exho "sum=$sum"
  sh option.sh 3 7
  sum=10
  $1,$2就是shell脚步预设的变量,默认设置好的,按顺序输入两个数字,默认赋值变量$1=3,$2=7.
  同样$3,$4,$5依次后推也是预设变量。
  4.脚本中逻辑判断if,if...else,if..elif..else
  4.1 vi iftest1.sh
  #! /bin/bash
  ##
  ##
  read -p "Input your score: " a
  if (($a
页: [1]
查看完整版本: Shell脚本编写