hc6538 发表于 2018-8-20 13:46:20

初学时的shell-shell

测试过程:vi test.sh 后把程序写入其中,保存退出。然后改变文件属性:chmod +x test.sh 最后执行:./test.sh  for语句测试:
  1)
  #!/bin/bash
  for num in 1 2 3
  do
  echo "hello,num=$num"
  done
  2)
  #!/bin/bash
  for ((i=1;i fortest.sh
  sed '1,$s/is/--end/' fortest.sh
  sed '1,$s/is/--end/g' fortest.sh
  sed '/is/=' fortest.sh
  引号测试:
  #!/bin/bash
  var=hello
  echo "var is $var"
  echo 'var is $var'
  echo "var is \$var"
  echo `ls`
  var2=date
  echo `$var2`
  case语句测试:
  #!/bin/bash
  for (( ;; ))
  do
  echo "please input a key:"
  read word
  case $word in
  1)
  echo "your chioce is the one"
  ;;
  2)
  echo "your chioce is the two"
  ;;
  3)
  echo "your chioce is the three"
  ;;
  q)
  echo "your choice is exit"
  exit
  ;;
  *)
  echo "illegal choice"
  exit
  esac
  done
  " $ "符号测试:
  #!/bin/bash
  echo "please run with more than one parm";
  echo "program name \$0:"$0;
  echo "first param \$1:"$2;
  echo "first param \$$:"$$;
  echo "first param \$*:"$*;
  数组的使用:
  #!/bin/bash
  hostip=("100","101","102","103","104","105","106","107","108","109","110")
  hostpass=("123456","123456","123456","123456","123456","123456","123456","123456","123456","123456","123456")
  i=1
  while [ $i -lt 12 ] ; do
  ssh root@10.0.2.hostip[$i]
  done
  重启别人电脑的shell:          #这个好像有点问题,需再测试下
  #!/usr/bin/expect
  spawn ssh root@10.0.2.120
  expect "password:"
  send "123456\n"
  expect "$"
  send "reboot\n"
  #expect "password:"
  #send "123456\n"
  expect eof
  查找文件,需指定查找目录和文件的修改时间:
  #!/bin/bash
  path=$1
  date=$2
  if [ -z $path ]
  then
  echo "Please input find path:(eg:/dev/abc/)"
  read path
  fi
  if [ -z $date ]
  then
  echo "Please input find date:(eg:2006-04-23)"
  read date
  fi
  ls -l $path --time-style=long-iso | grep "$date $time"
  递归算法:
  1)
  #!/bin/bash
  function myls()
  {
  local y=`ls`;
  echo $y;
  for z in $y;do
  if [ -d $z ];then
  echo "进入子目录";
  cd `pwd`/$z;
  myls;
  echo "返回上一级目录";
  cd..;
  fi
  done
  }
  echo "please input a directory:"
  read x
  cd $x
  myls;
  2)#!/bin/bash
  check_dir()
  {
  if [ -d $y ];then
  echo "$y是一个目录";
  ls -l $y
  else
  echo "$y是一个文件";
  fi
  }
  echo "please input a directory:"
  read y
  x=`ls $y`
  echo $x
  for y in $x;do
  check_dir
  done;
  备份脚本:
  #!/bin/bash
  /bin/tar -zcf /var/mail
  /bin/cp /var/mail.tar.gz /root
  查找目录:
  #!/bin/bash
  ls -l | grep ^d
  #输出当前目录下的所有目录
  更新ftp服务器上的文件:
  #!/bin/bash
  echo "open 10.0.2.224" > /tmp/ftp1.cmd
  echo "user ubunadm 123456" >> /tmp/ftp1.cmd
  echo "get `date +%Y`/`date +%Y%m`/`date +%d`/file01 /root/copy/file02" >> /tmp/ftp1.cmd
  ftp -nv < /tmp/ftp1.cmd
  echo "quit" >> /tmp/ftp1.cmd

页: [1]
查看完整版本: 初学时的shell-shell