1.1 shell脚本介绍

shell结构以及执行

cd shell/

vim first.sh

#!/bin/bash

##The first test shell script

##written by aming.

ls /tmp/

echo "This is the first script."

bash first.sh

 ./first.sh

sh first.sh

sh -x first.sh

date命令

date  日期

cal

yum -y install ntp

ntpdate time.windows.com

netpdate ntp.fudan.com

date +%T  Y y  m  d H M S s 

date -d "-2 days" +%F

shell自定义变量

vim 2.sh

#!/bin/bash

##

##

read -t 3 -p "please input a number: " number

echo $number

sh 3.sh

vim 3.sh

#! /bing/bash

##

##

echo "\$1=$1"

echo "\$2=$2"

echo  "\$0=$0"

echo "\$3=$o"

sh 3.sh

if逻辑判断

vim if.sh

#!/bin/bash

a=5

if [ $a -gt 10 ]

then

    echo "a>10"

elif [$a -lt 4 ]

then

    echo "a<4"

else

    echo "4

fi

> -gt  < -lt == eq != ne >= -ge <= le

1.6 if判断的几种用法

 touch 1.txt

if [ -f 1.txt ]; then echo ok; fi

if [ -d /tmp/ ]; then echo ok; fi

   -r -w -x 

 -n 不为空

 -z 为空

 if grep -q '^root:' /etc/passwd

if grep -q '^root:' /etc/passwd; then echo "root exist." ; fi

if [ -d /tmp/ ] && [ -f 1.txt ]; then echo ok; fi

 case选择

cd shell/

 vim case.sh

#! /bin//bash

read -p "Please input a number: " n

m=$[$n%2]

echo $m

case $m in

      1)

          echo "The number is jishu."

          ;;

      0)

          echo "The number is oushu."

          ;;

      *)

          echo "It is not jishu or oushu."

          ;;

esac

for循环

cd shell/

vim for.ch

#! /bin/bash

for i in `seq 1 10`

do

1.9 while循环

vim while.sh

#!/bin/bash

while :

do

   read -p "Please input a number: " m

   n=`echo $m |sed 's/[0-9]//g'`

   if [ -z "$n" ]

   then

      echo $m

      exit

   fi

done

sh wguke.sh

shell中断继续退出

vim for2.sh

#! /bin/bash

for i in `seq 1 10`

do

    echo $i

    if [ $i -eq 4 ]

    then

         break

    fi

   echo $i

done

shell函数

vim fun.sh


#!bin/bash

function mysum () {

  local   sum=$[$1+$2]

     echo $sum

}

a=1

b=2

mysum $a $b

echo $sum

2.2 shell数组

a=(1 2 3 4)

 echo ${a[@]}

 echo ${a[*]}

echo ${a[1]}  0 是显示第一个数字

a[4]=9

echo ${a[4]}

for i in `seq 0 9`; do a[$i]=$RANDOM; done ; echo ${a[@]}

for i in `seq 0 9`; do a[$i]=$RANDOM; done ; echo ${a[@]} |sed 's/ /\n/g'|sort

for i in `seq 0 9`; do a[$i]=$RANDOM; done ; echo ${a[@]} |sed 's/ /\n/g'|sort -n

unset a

for i in `seq 0 9`; do a[$i]=$RANDOM; done ; echo ${a[@]}

unset a[4]

echo ${a[@]

echo ${a[@]:0:4}