免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 884 | 回复: 0
打印 上一主题 下一主题

shell 编程基础 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-05-31 00:18 |只看该作者 |倒序浏览
1:在shell编程中的变量。
shell 变量(转换shell后就失效),环境变量(改变shell后仍有效)。Bash和pdksh中给变量赋值得方法一样(变量名后面跟上等号和变量值,如: var1=1,等号两边不能有空格),tcsh中使用:set var1 = 5(等号两边可以有空格也可没有) 。
对shell变量进行数字运算,使用expr命令:如,expr $a + $b (注意+两边的空格);expr 2 \* \( 3 + 4 \)
  特殊变量  
      $#:存储shell程序中命令行参数的个数
      $?:存储shell中上一个程序执行的返回值(0表示命令执行成功,非0有问题)
      $0:存储shell程序自己的名称
      $[1-n]:存储第[1-n]个命令行参数
      $*:存储shell脚本的所有参数(不包含$0)
      $@:存储shell脚本的所有命令行参数
      $$:存储shell脚本的进程号(pid)
      $!:存储上一个后台执行命令的进程号(pid)
        
2:使用哪一种命令外壳执行shell程序
    第一: 命令解释器  shell文件名。如:bash file1.sh
    第二:在shell脚本中的的首行指明由谁执行。如:#!/bin/bash
如果第一行非空字符为#!则使用后面指名的shell,如果第一行非空字符为#则使用C外壳,如果第一行非空字符不为#则使用B外壳。
    第三:在pdksh和bash下使用“.  文件名”(点后有空格),在tcsh下使用“source 文件名”
    第四:命令替换:略。
3:从标准输入读取变量的值
可通过命令行参数以及交互式输入变量(read),如:read  a 。
bash的流程控制语句
1)条件判断
. if-then语句,格式如下:
   if command_1
   then
        command_2
        command_3
    fi
    command_4
   在if-then语句中使用了命令返回值$?,即当command_1执行成功时才执行command_2 和command_3,而command_4总是执行.
   . if-then-else语句
   if command_1
   then
        command_2
   else
        command_3
   fi         
   .if嵌套及elif结构
        if command
        then
            command
        else
            if command
            then
                command
            else
                if command
                then
                    command
                fi
            fi
        fi
        改进:使用elif结构
        if command
        then
            command
        elif    command
        then   
            command
        elif    command
        then
            command
        fi
        elif结构同if结构类似,但结构更清淅,其执行结果完全相同.
.bash和pdksh中的case语句规则如下:
    case string1 in
       str1 )
         commands;;
       str2 )
         commands;;
       * )――――――――――――――缺省情况
         commands;;
    esac
2)循环控制语句(详细语法解释略)
.for语句
for var1 in list(用空格隔开各个选项)
    do
        commands
    done
或者:for var        列表需要在命令行输入
     do
        commands
     done
.while语句
while 表达式
do
           commands
        done
3)shift:移动shell程序的命令行参数
  语法格式:shift [n]
  如果有参数n,shift重命名位置参数,参数n+1对应与$1,n+2应与$2…,若为0则参数不变;若无参数则莫认为1,则参数应则参数应为非负数。
4)select 命令
  语法格式:
       select variable in list-of-items
       do
          commands
       done
  常 用于显示用户选择的被编号的菜单项,在标准输出中显示in之后的列表项,在每一项之前由数值作为前导。如果in被省略,则使用位置参数值。在显示列表项之 后显示PS3提示符提示用户输入内容,select把值赋给变量。若用户输入空行则菜单被重新显示。如果读入EOF(CTRL+D)则命令终止, select的退出状态是最后一条命令的执行结果。若无命令执行返回0。
   例:
   select mychoice in size information cfiles
   do
      case $mychoice in
        size)
          ls –s;;
        information)
          ls –l;;
        cfiles)
          ls *.c;;
      esac
   done
5)exit有两个作用:一是停止程序中其他命令的执行,二是设置程序的退出状态.n为返回值
   命令格式:exit [n]
6)break命令:强制程序从for,while或until循环中退出,n为退出循环的层次
   命令格式:break [n]
test的使用
. 使用test命令进行进行条件测试
      格式: test conditions
      test在以下四种情况下使用:
            a. 字符比较
            b. 两个整数值的比较
            c. 文件操作,如文件是否存在及文件的状态等
            d. 逻辑操作,可以进行and/or,与其他条件联合使用

      a. 测试字符数据: shell变量通常民政部下均作为字符变量
        str1 = str2 二者相长,相同
        str1 != str2    不同
        -n string   string不为空(长度不为零)
        -z string   string为空
        string      string不为空
    例:
        $ str1=abcd #在含有空格时必须用引号括起来
        $ test $str1=abcd
        $ echo $?
        0
        $ str1="abcd "
        $ test $str1=abcd
        $ echo $?
        1
    注意: 在test处理含有空格的变量时最好用引号将变量括起来,否则会出现错误的结果,因为shell在处理命令行时将会去掉多余的空格,而用引号括起来则可以防止shell去掉这些空格. 例:
            $ str1="    "
            $ test $str1
            $ echo $?
            1
            $ test "$str1"
            $ echo $?
            0
            $ test -n $str1
            test: argument expected
            $ test -n "$str1"
            $ echo $?
            0
            
    b. 整数测试: test与expr相同,可以将字符型变量转换为整数进行操作,expr进行       整数的算术运算,而test则进行逻辑运算.
         表达式         说明
         ---------------------------------------
         int1 -eq int2      相等?
         int1 -ne int2      不等?
         int1 -gt int2      int1 > int2 ?   
         int1 -ge int2      int1 >= int2 ?
         int1 -lt int2      int1  empty
            $ test -r empty
            $ echo $?
            0
            $ test -s empty
            1
            $ test ! -s empty
            $ echo $?
            0
      e. 测试条件之逻辑运算
        -a  And
        -o  Or
        例: $ test -r empty -a -s empty
            $ echo $?
            1
      f. 进行test测试的标准方法
         因为test命令在 shell编程中占有很重要的地位,为了使shell能同其他编程语言一样便于阅读和组织, Bourne Shell在使用test测试时使用了另一种方法:用方括号将整个test测试括起来:
         $ int1=4
         $ [ $int1 -gt 2 ]
         $ echo $?
         0
bash编程实例
实例1:判断/etc/shadow是否可执行
#!/bin/bash
if test -x /etc/shadow
then
        echo "the file is writeable"
else
        echo "the file is not writeable!"
fi
实例2:简单的菜单程序
#!/bin/bash
if test -x /etc/shadow
then
        echo "the file is writeable"
else
        echo "the file is not writeable!"
fi
实例3:完整的系统脚本/etc/rc.d/init.d/nfs

#!/bin/sh
#
# nfs This shell script takes care of starting and stopping
# the NFS services.
#
# chkconfig: - 60 20
# description: NFS is a popular protocol for file sharing across TCP/IP \
# networks. This service provides NFS server functionality, \
# which is configured via the /etc/exports file.
# probe: true
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
if [ ! -f /etc/sysconfig/network ]; then
    exit 0
fi
. /etc/sysconfig/network
# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0
[ -x /usr/sbin/rpc.nfsd ] || exit 0
[ -x /usr/sbin/rpc.mountd ] || exit 0
[ -x /usr/sbin/exportfs ] || exit 0
# Don't fail if /etc/exports doesn't exist; create a bare-bones version and continue.
[ -s /etc/exports ] || \
    { echo "#" > /etc/exports && chmod u+rw,g+r,o+r /etc/exports ; } || \
    { echo "/etc/exports does not exist" ; exit 0 ; }
# Number of servers to be started by default
RPCNFSDCOUNT=8
# NFSv3 only if kernel >= 2.2.18
OS_RELEASE=`uname --release`
OS_RELEASE_MINOR=`echo "$OS_RELEASE" | sed 's/\(^[0-9]\)\.\([0-9]*\).*/\2/'`
OS_RELEASE_VERSION=`echo "$OS_RELEASE" | sed
's/\(^[0-9]\)\.\([0-9]*\)\.\([0-9]*\).*/\3/'`
if [ "$OS_RELEASE_MINOR" -gt 2 ]; then
    RPCMOUNTDOPTS=
elif [ "$OS_RELEASE_MINOR" -eq 2 -a "$OS_RELEASE_VERSION" -ge 18 ]; then
    RPCMOUNTDOPTS=
else
    RPCMOUNTDOPTS="--no-nfs-version 3"Z
fi
if [ -n "$MOUNTD_PORT" ]; then
    RPCMOUNTDOPTS="$RPCMOUNTDOPTS --port $MOUNTD_PORT"
fi
# See how we were called.
case "$1" in
  start)
    # Start daemons.
    action "Starting NFS services: " /usr/sbin/exportfs –r
    if [ -x /usr/sbin/rpc.rquotad ] ; then
        echo -n "Starting NFS quotas: "
        daemon rpc.rquotad
        echo
    fi
    echo -n "Starting NFS mountd: "
    daemon rpc.mountd $RPCMOUNTDOPTS
    echo
    echo -n "Starting NFS daemon: "
    daemon rpc.nfsd $RPCNFSDCOUNT
    echo
    touch /var/lock/subsys/nfs
    ;;
  stop)
    # Stop daemons.
    echo -n "Shutting down NFS mountd: "
    killproc rpc.mountd
    echo
    echo -n "Shutting down NFS daemon: "
    killproc nfsd
    echo
    action "Shutting down NFS services: " /usr/sbin/exportfs –au
    if [ -x /usr/sbin/rpc.rquotad ] ; then
        echo -n "Shutting down NFS quotas: "
        killproc rpc.rquotad
        echo
    fi
    rm -f /var/lock/subsys/nfs
    ;;
  status)
    status rpc.mountd
    status nfsd
    if [ -x /usr/sbin/rpc.rquotad ] ; then
        status rpc.rquotad
    fi
    ;;
  restart)
    echo -n "Restarting NFS services: "
    echo -n "rpc.mountd "
    killproc rpc.mountd
    daemon rpc.mountd $RPCMOUNTDOPTS
    /usr/sbin/exportfs –r
    touch /var/lock/subsys/nfs
    echo
    ;;
  reload)
    /usr/sbin/exportfs –r
    touch /var/lock/subsys/nfs
    ;;
  probe)
    if [ ! -f /var/lock/subsys/nfs ] ; then
      echo start; exit 0
    fi
    /sbin/pidof rpc.mountd >/dev/null 2>&1; MOUNTD="$?"
    /sbin/pidof nfsd >/dev/null 2>&1; NFSD="$?"
    if [ $MOUNTD = 1 -o $NFSD = 1 ] ; then
      echo restart; exit 0
    fi
    if [ /etc/exports -nt /var/lock/subsys/nfs ] ; then
      echo reload; exit 0
    fi
    ;;
  *)
    echo "Usage: $0 {start|stop|status|restart|reload}"
    exit 1
esac
exit 0
判断:
#!/bin/sh
  myPath="/var/log/httpd/"
  myFile="/var /log/httpd/access.log"
  #这里的-x 参数判断$myPath是否存在并且是否具有可执行权限
  if [ ! -x "$myPath"]; then
  mkdir "$myPath"
  fi
  #这里的-d 参数判断$myPath是否存在
  if [ ! -d "$myPath"]; then
  mkdir "$myPath"
  fi
  #这里的-f参数判断$myFile是否存在
  if [ ! -f "$myFile" ]; then
  touch "$myFile"
  fi
  #其他参数还有-n,-n是判断一个变量是否是否有值
  if [ ! -n "$myVar" ]; then
  echo "$myVar is empty"
  exit 0
  fi
  #两个变量判断是否相等
  if [ "$var1" = "$var2" ]; then
  echo '$var1 eq $var2'
  else
  echo '$var1 not eq $var2'
  fi


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/25969/showart_719825.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP