shell_编程2(语法)

来源:互联网 发布:高级软件开发工程师 编辑:程序博客网 时间:2024/05/22 14:33

1.判断

#if判断结构     if expression;then    commandfi#if/else判断结构if expression;then    commandelse    commandfi#嵌套ifif expression1;then    command1elif expression2;then    command2elif expression3;then    command3    fi#case判断case VAR invar1) command1;;var2) command2;;var3) command3;;*) command;;esac

2.循环

#带列表的for循环for VARIABLE in (list)do    commadndone#不带列表的for循环for VARIABLEdoprin    commanddone#类c的for循环for ((expression;expression2;expression3))do    commanddone#while循环while expressiondo    commanddone#util循环until expressiondo    commanddonef#打印乘法口诀表1 #!/bin/sh2 #fun print 9*93 for ((i=0;i<=9;i++))4 do5     for ((j=1;j<=9;j++))6     do7         if [[ ${i} -ge ${j} ]]; then8             let mul=${i}*${j}9             echo -n "${i}*${j}=${mul} "10         else11             break12         fi13     done14     echo15 done

3.函数

function FUNCTION_NAME(){    command1    command2}FUNCTION_NAME(){    command1    command2}  1 #!/bin/sh  2 #usage : *.sh arg1  3 #fun   :  print arg1 file colmns  4 arguJudge(){  5     echo "Usage: *.sh  fileName "  6     return 1  7 }  8   9 if [[ $# -lt 1 ]]; then 10     arguJudge 11 fi 12  13 FILE=$1 14 countLine(){ 15     local i=0 16     while read line 17     do 18         let ++i 19     done < ${FILE}#求和#!/bin/bashTOTAL=0until [ $# -eq 0 ]do    let "TOTAL=TOTAL+$1"    shiftdoneecho "$TOTAL"

4.加载函数库

函数库11

#函数库 libbase.sh #!/bin/bash_checkFileExit_B_L(){if [ -f $1 ]; then    echo "Files: $1 exits"else    echo "Files: $1 not exits"fi}#test libbase.sh#!/bin/bashsource ./Leolib/libbase.sh_checkFileExit_B_L /etc/passwd_checkFileExit_B_L /var/log/message

4.IO

  • >    标准输出覆盖重定向
  • >>    标准输出追加重定向
  • >&   表示输出重定向  commadn > stderr.log 2>&1 如果有错误也输出到stderr.log
  • <    标准输入重定向
  • |    管道

5.exec

exec < file 把file文件的内容作为exec的输入exec > file exec的结果输出到file中exec num< 指定文件描述符exec num<&-  关闭文件描述符
原创粉丝点击