Shell Advanced Programming

Source: Internet
Author: User
Tags variable scope

  • Conditional Select if statement

        选择执行: 注意:if语句可嵌套     单分支    if 判断条件;then    条件为真的分支代码    fi    双分支    if 判断条件; then    条件为真的分支代码    else条件为假的分支代码    fi    多分支    if 判断条件1; then    条件为真的分支代码    elif 判断条件2; then    条件为真的分支代码    elif 判断条件3; then    条件为真的分支代码    else以上条件都为假的分支代码    fi    逐个条件进行判断,第一次遇为“真”条件时,执行其分支,而后结束整个if语    句
  • If example
    Execute commands According to the exit status of the command

    If ping-c1-w2 station1 &>/dev/null; Then
    Echo ' Station1 is up '
    elif grep "Station1" ~/maintenance.txt &>/dev/null
    Then
    Echo ' Station1 is undergoing maintenance '
    else Echo ' Station1 is unexpectedly down! ' exit 1
    Fi

            条件判断:case语句        case 变量引用 in        PAT1)                     分支1                        ;;        PAT2)                        分支2        ;;                 ...*)        默认分支        ;;        esac        case支持glob风格的通配符:        *: 任意长度任意字符        ?: 任意单个字符        []:指定范围内的任意单个字符        a|b: a或b
      • For loop

             for 变量名 in 列表;do    循环体    done    执行机制:    依次将列表中的元素赋值给“变量名”; 每次赋值后即执行一次循环体; 直到列表中的元素    耗尽,循环结束

    List Generation Method:

    (1) Give the list directly
    (2) List of integers:
    (a) {start: End
    (b) $ (SEQ [start [step]] end)
    (3) command to return a list
    (4) using glob, such as:. sh
    (5) variable reference; [email protected], $

      • While loop

            while CONDITION; do    循环体    done    CONDITION:循环控制条件;进入循环之前,先做一次判断;每一次循环之后会再次判断;条件    为“true”,则执行一次循环;直到条件测试状态为“false”终止循环    因此:CONDTION一般应该有循环控制变量;而此变量的值会在循环体不断地被修正    进入条件:CONDITION为true    退出条件:CONDITION为false
      • Until cycle
        Until CONDITION; Do
        Loop body
        Done
        Entry condition: CONDITION is False
        Exit Condition: CONDITION is True

            循环控制语句continue    用于循环体中    continue [N]:提前结束第N层的本轮循环,而直接进入下一轮判断;最内层为第1层    while CONDTIITON1; do    CMD1    ...    if CONDITION2; then    continue    fi    CMDn    ...    done    循环控制语句break    用于循环体中    break [N]:提前结束第N层循环,最内层为第1层    while CONDTIITON1; do    CMD1...if CONDITION2; then    breakfiCMDn...done

    Example: doit.sh

            #!/bin/bash         Name: doit.sh        Purpose: shift through command line arguments        Usage: doit.sh [args]        while [ $# -gt 0 ] # or (( $# > 0 ))        doecho $*        shiftdone

    Example: shift.sh

            #!/bin/bash        #step through all the positional parameters        until [ -z "$1" ]        doecho "$1"        shiftdoneecho        创建无限循环        while true; do        循环体        done         until false; do        循环体        Done    特殊用法    while循环的特殊用法(遍历文件的每一行):    while read line; do    循环体    done < /PATH/FROM/SOMEFILE    依次读取/PATH/FROM/SOMEFILE文件中的每一行,且将行赋值给变量line

    Practice
    Scan each line of the/etc/passwd file, if the Gecos field is found to be empty, populate the user name and the unit phone as 62985600, and prompt the
    The user's Gecos information was modified successfully.

             #!/bin/bash         while read line ;do                         gecos=$(echo $line |cut -d: -f5)                         if [ -z "$gecos" ];then                                         UserName=$(echo $line |cut -d: -f1)                                         usermod -c "$UserName 62985600" $UserName                                         echo "$UserName‘s gecos changed"                         fi         done < /etc/passwd

    Write a script, the system will be existing users to determine the identity of the user, if CENTOS7, the UID greater than 1000 users will be judged as Comm user, and the second decision is SYS user, if it is CENTOS6, the UID is greater than 500 users are judged as Comm user, Conversely sys user. Output format is as follows
    Root:sys User
    ......
    Liubei:comm User

             #!/bin/bash         release=$(cat /etc/centos-release| sed -r ‘s/.* ([0-9]+)..*/\1/‘)         while read line; do                 uid=$(echo $line | cut -d: -f3)                 name=$(echo $line | cut -d: -f1)                 if [ $release = 6 -a $uid -lt 500 ] || [ $release = 7 -a $uid -lt 1000 ]; then                         echo "$name: sys user"                 else                         echo "$name: comm user"                 fi             done < /etc/passwd

    Find partitions with partition utilization greater than 10% and display the results as follows:
    /dev/sda1 'll be full:33%
    /dev/sda2 'll be full:99%

      #!/bin/bash DF |grep/dev/sd |while Read Line;do used=$ (echo $line |tr  -S ""% |cut-d%-f5) name=$ (echo $line |cut-d ""-f1) if (($used > ) and then echo "$name would be is full: $used%" fi don E  
      • Special usage

            双小括号方法,即((…))格式,也可以用于算术运算    双小括号方法也可以使bash Shell实现C语言风格的变量操作    I=10((I++))    for循环的特殊格式:    for ((控制变量初始化;条件判断表达式;控制变量的修正表达式))    do循环体    done控制变量初始化:仅在运行到循环代码段时执行一次    控制变量的修正表达式:每轮循环结束会先进行控制变量修正运算,而后再做条件判断    for ((i=1;i<=100;i++));do                    let sum+=i    done    echo sum=$sum    select循环与菜单    select variable in list    do    循环体命令    done    select 循环主要用于创建菜单,按数字顺序排列的菜单项将显示在标准错误上,并显示 PS3 提示符,等待用户输入    用户输入菜单列表中的某个数字,执行相应的命令    用户输入被保存在内置变量 REPLY 中[][][]    select 是个无限循环,因此要记住用 break 命令退出循环,或用 exit 命令终止脚本。也可以按    ctrl+c 退出循环    select 经常和 case 联合使用    与 for 循环类似,可以省略 in list,此时使用位置参量

    Exercise: Create a la carte system for a restaurant with a shell.
    Executes the script, which lists the main menu, as follows
    What would you like to eat?
    1) Rice
    2) face
    3) Dumplings
    4) do not eat

    Waiting for the user to select
    If you choose 1, then ask, select after the quote
    1) Fried Rice
    2) Rice bowls
    3) Wooden Barrel rice
    If you choose 2, ask again
    1) Fried Noodles
    2) Cover face
    3) Ramen noodles
    4) Mix Noodles
    If you choose 3, ask again
    1) pork and green onions
    2) Vegetarian Delicacies
    3) Leek Eggs
    After each selection, the final price will be quoted, such as
    Wooden barrel Rice: 10 RMB
    If you select 4, exit

            #!/bin/bash ps3= "Please choose your food:" echo "What To Eat" Caidan () {Select menu in rice noodles                                        dumplings do not eat; do case $REPLY in 1) Select fan in fried rice with rice bowl wooden barrel meal return; do                                                Case $REPLY in 1) echo "Fried rice: ten"; break 2;;                                                2) echo "Rice bowl:"; break 2;;                                                3) echo "Cask rice:"; break 2;;                                        4) Caidan;                        Esac done;;                                                2) Select Mian in noodle noodle noodles with noodles back; do case $REPLY in                                                1) echo "Chow Mein: Ten"; break 2;;                                                2) echo "Cover face:"; break 2;; 3) echo "ramen:"; break 2;;                                                4) echo "Mixed noodles:"; break 2;;                                        5) Caidan;                        Esac done;;                                                3) Select Jiaozi in pork onion vegetarian delicacies leek egg return                                                1) echo "Pork and green onion: ten"; break 2;;                                                2) echo "vegetarian delicacies:"; break 2;;                                                3) echo "Leek eggs:"; break 2;;                                        4) Caidan;                        Esac done;;                4) Exit; Esac done} Caidan


    Signal Capture Trap
    Trap ' trigger command ' signal
    When a custom process receives a specified signal from the system, it executes the triggering instruction without performing the original operation
    Trap ' signal
    Operations that ignore signals
    Trap '-' signal
    Operation to restore the original signal
    Trap-p
    column-defined signal operation

    Trap Example

            #!/bin/bash        trap ‘echo “signal:SIGINT"‘ int         trap -p         for((i=0;i<=10;i++));do                 sleep 1                echo $i         done         trap ‘‘ int         trap -p         for((i=11;i<=20;i++));do                sleep 1                 echo $i         done         trap ‘-‘ int         trap -p         for((i=21;i<=30;i++));do                 sleep 1                 echo $i         done
    • function Introduction

          函数function是由若干条shell命令组成的语句块,实现代码重用和模块化编程    它与shell程序形式上是相似的,不同的是它不是一个单独的进程,不能独立运行,而是shell程序的一部分    函数和shell程序比较相似,区别在于:    1.Shell程序在子Shell中运行    2. 而Shell函数在当前Shell中运行。因此在当前Shell中,函数可以对shell中变量进行修改定义函数? 函数由两部分组成:函数名和函数体 ? help function ? 语法一:function f_name{...函数体...}? 语法二:function f_name (){...函数体...}? 语法三:f_name (){...函数体...}    函数使用    ? 函数的定义和使用: – 可在交互式环境下定义函数 – 可将函数放在脚本文件中作为它的一部分 – 可放在只包含函数的单独文件中 ? 调用:函数只有被调用才会执行    调用:给定函数名    函数名出现的地方,会被自动替换为函数代码    ? 函数的生命周期:被调用时创建,返回时终止    检查载入函数    使用set命令检查函数是否已载入。set命令将在shell中显示所有的载入函    数

      Example:

        Set findit= () {if [$#-lt 1]; the echo "Usage:findit file";    Return 1 fi Find/-name $1-print} ... Delete Shell functions now, after making some changes to the function, you need to delete the function so that it is not available to the shell. Use the unset command to complete the DELETE function command format: unset function_name Example: unset findit and then typing the SET command, the function will no longer display the environment function so that the child process can also use the Declaration: Expo rt–f function_name View: The Export-f or DECLARE-XF function can accept arguments: Pass parameters to the function: When the function is called, the given argument list is separated by a blank space after the function name, for example "TestFunc arg1 a    Rg2 ... " In the function body, you can use $, $, ... Call these parameters; You can also use [email protected], $*, $ #等特殊变量 horse function Variable scope: Environment variable: current shell and child shell valid local variable: only valid for the current shell process, the execution script will start Dedicated child shell process; Therefore, the local variable is scoped to the current shell script file, including the function local variable in the script: the function's life cycle; The variable is destroyed automatically when the function ends Note: If there is a local variable in the function, if its name is the same as the local variable, use the local variable in the function Methods for defining local variables local name=value  
    • Function Recursive example

          函数递归:    函数直接或间接调用自身    注意递归层数    递归实例:    阶乘是基斯顿·卡曼于 1808 年发明的运算符号,是数学术语    一个正整数的阶乘(factorial)是所有小于及等于该数的正整数的积,并且有0的阶乘为1,自然数n的    阶乘写作n!    n!=1×2×3×...×n阶乘亦可以递归方式定义:0!=1,n!=(n-1)!×n    n!=n(n-1)(n-2)...1    n(n-1)! = n(n-1)(n-2)!    #!/bin/bash    #fact() {            if [ $1 -eq 0 -o $1 -eq 1 ]; then            echo 1            else            echo $[$1*$(fact $[$1-1])]            fi    }    fact $1    ×××    fork×××是一种恶意程序,它的内部是一个不断在fork进程的无限循环,实质是一个简单的递归    序。由于程序是递归的,如果没有任何限制,这会导致这个简单的程序迅速耗尽系统里面的所有资    源    函数实现    :(){ :|:& };:    bomb() { bomb | bomb & }; bomb    脚本实现    cat Bomb.sh    #!/bin/bash    ./$0|./$0&
    • Array

          变量:存储单个元素的内存空间    数组:存储多个元素的连续的内存空间,相当于多个变量的集合    数组名和索引    索引:编号从0开始,属于数值索引    注意:索引可支持使用自定义的格式,而不仅是数值格式,即为关联    索引,bash4.0版本之后开始支持    bash的数组支持稀疏格式(索引不连续)    声明数组:    declare -a ARRAY_NAME    declare -A ARRAY_NAME: 关联数组    注意:两者不可相互转换

    Array Assignment

            Assignment of an array element: (1) Only one element is assigned at a time; Array_name[index]=value weekdays[0]= "Sunday weekdays[4]=" Thurs        Day (2) assigns all elements at once: Array_name= ("VAL1" "VAL2" "VAL3" ...)        (3) Assign only specific elements: array_name= ([0]= "VAL1" [3]= "VAL2" ...) (4) Interactive array value pairs assignment read-a array displays all arrays: Declare-a references array elements: ${array_name[i Ndex]} Note: Omitting [INDEX] means referencing an element with subscript 0 referencing an array of all elements: ${array_name[*]} ${array_name[@]} The length of the array Degrees (number of elements in the array): ${#ARRAY_NAME [*]} ${#ARRAY_NAME [@]} to delete an element in the array: causes sparse formatting Unse        T Array[index] Delete the entire array unset array data processing elements in the reference array: Array slice: ${array[@]:offset:number} Offset: Number of elements to skip numbers: all elements after the offset of the number of elements to be fetched ${array[@]:offset} append elements to the array: array[${#A       Rray[*]}]=value associative array: declare-a array_name array_name= ([idx_name1]= ' val1 ' [idx_name2]= ' val2 ' ...) Note: Associative arrays must be declared before they are called 

    Example
    Generates 10 random numbers stored in an array and finds its maximum and minimum values

            #!/bin/bash        declare -a rand        declare -i max=0        declare –i min=32767        for i in {0..9}; do                rand[$i]=$RANDOM                echo ${rand[$i]}                [ ${rand[$i]} -gt $max ] && max=${rand[$i]}                [ ${rand[$i]} -lt $min ] && min=${rand[$i]}                done        echo "Max: $max Min:$min"

    Example
    Write a script that defines an array in which all the elements in the/var/log directory end in. log
    The sum of the number of rows in the file to be labeled as even

            #!/bin/bash        #declare -a files        files=(/var/log/*.log)        declare -i lines=0        for i in $(seq 0 $[${#files[*]}-1]); do                if [ $[$i%2] -eq 0 ];then                let lines+=$(wc -l ${files[$i]} | cut -d‘ ‘ -f1)                fi        done        echo "Lines: $lines."

    Shell Advanced Programming

    Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.