关闭

linux shell 编程实例

922人阅读 评论(0) 收藏 举报
分类:


http://blog.chinaunix.net/uid-24929997-id-3060653.html

我不喜欢看太多文字性的东西,我喜欢源码实例直接运行,在实践中了解shell的用法。故其他的原理和使用方法不多说,请参考其他的文章。

1、case.sh

#!/bin/bash
# script to test case statement
action="update"
case $action in
        "update")
                echo "update the db"
                ;;
        "select")
                echo "select from db"
                ;;
        "delete")
                echo "delete from db"
                ;;
        *)
                echo "no action"
                ;;
esac
echo ok;

2、datelog.sh

#!/bin/bash
#datelog.sh 日志文件
  current_date=`date ""+%Y%m%d` #当前的日期( 年月日 )
  todaylog="log/${current_date}.log" #今天的日志文件名
  #如果日志文件不存在,创建一个
  if [ ! -f $todaylog ]
    then
       mkdir log
        touch $todaylog
  fi
  #输出日志到日志文件
  log_time_format=`date "+%Y-%m-%d %T"`
  echo "${log_time_format} commands start.....">>${todaylog}
  # commands blocks
  sleep 2
  log_time_format=`date "+%Y-%m-%d %T"`
  echo "${log_time_format} commands end!">>${todaylog} #结束时记录日志

3、for.sh

echo start
for i in 1 2 3 4 5
do
        echo "welcome $i times"
done
for (( i = 0; i <= 5; i++ ))
do
      echo "welcome $i 次数"
done
for(( i = 1; i <= 5; i++  ))
do
        for(( j = 1; j <= 5; ++j ))
        do
                echo -n "$i "
        done
        # print a new line  换行
        echo ""
done
exit 0
for i in [ /root/netbean_workspace/cpp/HTML5Application/public_html/log/dustbin/*.log ]
do
    rm -r $i
    echo "$i has been deleted!"
done

4、function.sh

#!/bin/bash
  #hello
echo start
  function hello(){     #声明函数
    echo "Hello!"   #函数的主体,输出"Hello!"
  }           #函数结束
hello       #调用函数
function hello_param(){
    echo "Hello! The first parameter is '$1'.";
    echo  "第二个参数为:$2";
    echo "使用换行符或者;作为语句结束符"
}
hello_param good 你好
. fun_hello.sh #导入fun_hello.sh文件
fun_hello #调用fun_hello.sh里面的函数
echo $?   #输出上一个函数返回的状态值(一般成功是返回0,其它值为失败)
unset fun_hello #用unset function-name 取消载入的变量和函数
#fun_hello #因为已经取消载入,再次调用会出错

echo ok





fun_hello.sh

#!/bin/bash
#fun_hello.sh
function fun_hello(){
  echo "fun_hello!"
  return 1
}

5、getopts.sh

#!/bin/bash
#getopts 获取多个命令行参数。./getopts -ah
ALL=false
HELP=false
FILE=false
VERBOSE=false
while getopts ahfvc: OPTION   #将ahfvc依次传给OPTION  c后面的:表示-c时需传入参数
do
case ${OPTION} in
  a)
    ALL=true
    echo "ALL IS ${ALL}"
    ;;
  h)
    HELP=true
    echo "HELP IS ${HELP}"
    ;;
  f)
    FILE=true
    echo "FILE IS ${FILE}"
    ;;
  v)
    VERBOS=false
    echo "VERBOSE IS ${VERBOSE}"
    ;;
  c) #getopts -c hehe
    c=${OPTARG}
    echo "c value is $c"
    ;;
  \?)
    echo "`basename $0` -[a h f v] -[c value] file"
    ;;
  esac
done

6、if.sh

#! /bin/sh
# ifmkdir
#将脚本参数传入系统命令
#此处检测目录是否为空
DIRECTORY=$1
if [ "$DIRECTORY" = ""] ; then
 echo "Usage: `basename $0` directory to create"
 exit 1
fi
if [ -d $DIRECTORY ] 
then : # do nothing
else
 echo "The directory does exist"
 echo -n "Create it now? [y..n] :"
 read ANS
 if [ "$ANS" = "y" ] || [ "$ANS" = "Y" ]
 then
  echo "creating now"
  mkdir $DIRECTORY >/dev/null 2>&1
  if [ $? != 0 ]; then
   echo "Errors createing the directory $DIRECTORY" >&2
   exit 1
  fi
 else : # do nothing
 fi
fi

if [ "13" -lt "11" ] #如果13小于11
then         #那么
    echo "13<11"   #输出"13<11"
elif[ "13" -lt "12" ] #如果13小于12
then#那么
    echo "13<12"   #输出"13<12"
else         #否则
    echo "13>=12" #输出"13>=12"
fi


7、kill_process.sh

#!/bin/bash
#kill_process.sh
  #取得当前进程号
  current_pid=$$
   echo $current_pid
  #获得特定进程号并重定向到一个临时文件中
  ps -aux | grep "sh" | grep -v "grep" | awk '{print $2}' >/tmp/${current_pid}.txt
  #commands start
  for pid in `cat /tmp/${current_pid}.txt`
  do
  {
    echo "kill -9 $pid"
    #kill -9 $pid
  }
  done 
gedit /tmp/${current_pid}.txt
rm -f /tmp/${current_pid}.txt  #脚本运行结束前删除该日志文件

8、read.sh

#!/bin/sh                               
osch=0
echo "1. unix(sun os)"
echo "2. linux(red hat)"
echo -n "select your os choice [1 or 2] ?"
read osch
if [ $osch -eq 1  ]
then
        echo "you pick up unix"
else
        # nested if
        if [ $osch -eq 2 ]
        then
                echo "you pick up linux"
        else
                echo "what you donot like unix/linux"
        fi
fi

9、readTXT.sh

#!/bin/sh readTXT.sh
echo "start"
#line1="hehe"
#line2="lala"
exec 4<&0 0<stock.txt
read line1
read line2
exec 0<&4
echo $line1
echo $line2

10、test.sh

#!/bin/sh
# see whether arguments is positive
if [ $# -ne 1 ]
then
        echo "$0 : you must give/supply one integers"
        exit 1
fi
if test $1 -gt 0
then
        echo "$1 number is postivie"
else
        echo "$1 number is negative"
fi
echo ok

11、trap.sh

#!/bin/bash
#trap.sh  trap捕捉信号
trap 'exitprocess' 2 #捕捉到信号2之后执行exitprocess function
LOOP=0
function exitprocess()
{
    echo "按下了ctrl+c"
    echo "You Just hit <CTRL-C>, at number $LOOP"
    echo "I will now exit"
    exit 1
}
while :   # 循环直到捕捉到信号(注意中间的空格) 
do
    LOOP=$[ $LOOP+1 ]
    echo $LOOP
    sleep 1
done
echo "不能运行到!"

12、while.sh

#!/bin/bash
# test while loop
n=2
i=0
while [ $i -le 10 ]
do
        echo "$n * $i = `expr $i \* $n`" #计算
        i=`expr $i + 1` #自增
done
echo ok







0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1800131次
    • 积分:25479
    • 等级:
    • 排名:第242名
    • 原创:783篇
    • 转载:382篇
    • 译文:0篇
    • 评论:225条
    我的技术博客
    最新评论