Advanced Bash script, classic usage and cases, advanced bash

Source: Internet
Author: User
Tags glob egrep

Advanced Bash script, classic usage and cases, advanced bash
In linux, Bash scripts are very basic knowledge. You may feel very high when you listen to the scripts. Just like starting from the beginning, you may feel that script writing is a great tool. Although complicated scripts are very easy to understand, when we master the usage and skills of these scripts and practice more, we will always become a handy script giant one day. The role of a script in production must not be mentioned in the editor. Everyone knows that writing script 6 can save a lot of complicated operations and relieve their work pressure. Well, let's just talk about it. Next, we will show how to use the Bash script. I. Conditional selection and judgment (if ·, case) II. Four loops (for, while, until, select) 3. Some commands and techniques in the loop (continue, break, shift ...) iv. Signal capture trap I. Condition Selection and determination: (1) Condition SelectionIf1. Usage formatIfCondition 1; ThenBranch code with true conditionElifCondition 2; ThenCondition: True branch code elif judgment Condition 3; then condition: True branch codeElseAll of the preceding conditions are false branch codes.FiDetermine by condition. When the condition is true for the first time, execute its branch and end the entire if. 2. Typical Cases: ① determine the age

#! / bin / bash
read -p "Please input your age:" age
if [[$ age = ~ [^ 0-9]]]; then
    echo "please input a int"
    exit 10
elif [$ age -ge 150]; then
    echo "your age is wrong"
    exit 20
elif [$ age -gt 18]; then
    echo "good good work, day day up"
else
    echo "good good study, day day up"
fi
 Analysis: Please enter the age, first judge whether the input contains characters other than numbers, if there is, report an error; if not, continue to judge whether it is less than 150 and greater than 18.

② Judging the score
#! / bin / bash
read -p "Please input your score:" score
if [[$ score = ~ [^ 0-9]]]; then
    echo "please input a int"
    exit 10
elif [$ score -gt 100]; then
    echo "Your score is wrong"
    exit 20
elif [$ score -ge 85]; then
    echo "Your score is very good"
elif [$ score -ge 60]; then
    echo "Your score is soso"
else
    echo "You are loser"
fi
 Analysis: Please enter the score, first judge whether the input contains characters other than numbers, if yes, report an error; if not, continue to judge whether it is greater than 100, greater than 85, and greater than 60.

  (2) Condition judgment case 1. Usage format case $ name in; PART1) cmd ;; PART2) cmd ;; *) cmd ;; esac Note: case supports glob-style wildcards: arbitrary: *: Character []: any single character within the specified range a | b: a or b 2. Case: judge yes or no
#! / bin / bash
read -p "Please input yes or no:" anw
case $ anw in
[yY] [eE] [sS] | [yY])
    echo yes
    ;;
[nN] [oO] | [nN])
    echo no
    ;;
*)
    echo false
    ;;
esac
 Analysis: Please enter yes or no, and answer Y / y, yes, the combination of all capitalization is yes; answer N / n, No, the combination of all capitalization is no.

  Two, four loops (1) for 1, usage format ① for name in list; do loop body done ② for ((exp1; exp2; exp3)); do cmd done
exp1 is executed only once, which is equivalent to while embedded in for

③ Execution mechanism: assign the elements in the list to the "variable name" in sequence; after each assignment, the loop body is executed once; until the elements in the list are exhausted, the end of the loop is a list representation method, which can be glob wildcards, such as {1. .10}, * .sh; also variable references, such as: `seq 1 $ name` 2. Case: ① Find the sum of (1 + 2 + ... + n)
sum = 0
read -p "Please input a positive integer:" num
if [[$ num = ~ [^ 0-9]]]; then
    echo "input error"
elif [[$ num -eq 0]]; then
    echo "input error"
else
    for i in `seq 1 $ num`; do
        sum = $ [$ sum + $ i]
    done
    echo $ sum
fi
unset zhi
 Analysis: The initial value of sum is 0, please enter a number, first determine whether the input contains characters other than numbers, if yes, an error will be reported; if there is no judgment, it is 0, if it is not 0, enter the for loop, and the range of i is 1 ~ input The number of times, each cycle is sum = sum + i, the cycle ends, and finally the sum value is output.

② Find the sum of (1 + 2 + ... + 100)

for ((i = 1, num = 0; i <= 100; i ++)); do
        [$ [i% 2] -eq 1] && let sum + = i
done
echo sum = $ sum
 Analysis: i = 1, num = 0; when i <= 100, enter the loop, if i ÷ 2 takes the remainder = 1, then sum = sum + i, i = i + 1.

 

(2) while

1. Usage format while loop control condition; do loop done loop control condition; before entering the loop, make a judgment first; after each loop, the judgment will be made again; the condition is "true", then execute a loop; until the condition test status is "False" Terminate the loop 2. Special usage (traverse each line of the file): while read line; do control variable initialization loop body done </ PATH / FROM / SOMEFILE or cat / PATH / FROM / SOMEFILE | while read line; do loop The body done reads each line in the / PATH / FROM / SOMEFILE file in turn, and assigns the line to the variable line 3. Case: ① The sum of all positive and odd numbers within 100
sum = 0
i = 1
while [$ i -le 100]; do
if [$ [$ i% 2] -ne 0]; then
    let sum + = i
    let i ++
else
    let i ++
fi
done
echo "sum is $ sum"
 Analysis: The initial value of sum is 0, and the initial value of i is 1. Please enter a number to determine whether the input contains characters other than numbers. If yes, an error will be reported; if i <100, enter the loop and judge i ÷ 2 Whether the remainder is not 0, when it is not 0, it is an odd number, sum = sum + i, i + 1, 0, i + 1; the loop ends, and the sum value is finally output.

  (3) until loop 1. Usage unitl loop condition; do loop done Enter condition: loop condition is true; exit condition: loop condition is false; just the opposite of while, so it is not commonly used, just use while. 2. Case Monitor xiaoming users, kill after logging in
until pgrep -u xiaoming &> / dev / null; do
        sleep 0.5
done
pkill -9 -u xiaoming
 Analysis: Scan every 0.5 seconds until the xiaoming user is found to log in, kill the process, and exit the script to monitor user login.

  (4) Select loop and menu 1. Usage select variable in list do loop body command done ① The select loop is mainly used to create a menu, the menu items arranged in numerical order will be displayed on the standard error, and the PS3 prompt will be displayed, wait User input ② The user enters a number in the menu list and executes the corresponding command ③ The user input is stored in the built-in variable REPLY ④ select is an infinite loop, so remember to use the break command to exit the loop, or use exit to terminate the script . You can also press ctrl + c to exit the loop. ⑤ select and are often used in combination with case. ⑥ Similar to the for loop, you can omit the in list, and use the position parameter at this time. 2. Case: generate a menu and display the selected price
PS3 = "Please choose the menu:"
select menu in mifan huimian jiaozi babaozhou quit
do
        case $ REPLY in
        1 | 4)
                echo "the price is 15"
                ;;
        2 | 3)
                echo "the price is 20"
                ;;
        5)
                break
                ;;
        *)
                echo "no the option"
        esac
done
 Analysis: PS3 is the prompt for selection, automatically generates a menu, select 5break to exit the loop.

 

 Third, some usages in the loop (1) Loop control statement continue [N]: End the current round of the Nth layer in advance, and directly enter the next round of judgment; the innermost layer is the first layer break [N]: End early The Nth layer loop, the innermost is the first layer Example: while CONDTITON1; do CMD1 if CONDITION2; then continue / break fi CMD2 done 2, Case: ① Seeking (1 + 3 + ... + 49 + 53 + ... +100) and
#! / bin / bash
sum = 0
for i in {1..100}; do
        [$ i -eq 51] && continue
        [$ [$ i% 2] -eq 1] && {let sum + = i; let i ++;}
done
echo sum = $ sum
 Analysis: Do a loop of 1 + 2 + ... + 100, when i = 51, skip this loop, but continue the whole loop, the result is: sum = 2449

 ② Find the sum of (1 + 3 + ... + 49)
#! / bin / bash
sum = 0
for i in {1..100}; do
        [$ i -eq 51] && break
        [$ [$ i% 2] -eq 1] && {let sum + = i; let i ++;}
done
echo sum = $ sum
 Analysis: do 1 + 2 + ... + 100 loop, when i = 51, jump out of the entire loop, the result is: sum = 625

  (2) Cyclic control shift command 1. Function It is used to shift the parameter list list to the left a specified number of times. The leftmost parameter is deleted from the list, and the parameters behind it continue to enter the loop 2. Case: ① Create multiple users specified
#! / binbash
if [$ # -eq 0]; then
        echo "Please input a arg (eg:` basename $ 0` arg1) "
        exit 1
else
        while [-n "$ 1"]; do
                useradd $ 1 &> / dev / null
                shift
        done
fi
 Analysis: If there is no input parameter (the total number of parameters is 0), an error is prompted and exit; otherwise, enter the loop; if the first parameter is not a null character, create a user named after the first parameter and remove the first For a parameter, move the immediately following parameter to the left as the first parameter until there is no first parameter and exit.

 ② Print the characters of right triangle
#! / binbash
while (($ #> 0))
do
        echo "$ *"
        shift
done
 

(3) Return value result

true will always return a successful result: null command, do nothing, return a successful result false will always return an error result Create an infinite loop while true; do loop body done (4) The loop can be executed in parallel, making the script run faster 1, usage for name in list; do {loop body} & done wait 2. Example: Search for the UP ip address in the network segment of the specified ip (subnet mask is 24)
read -p "Please input network (eg: 192.168.0.0):" net
echo $ net | egrep -o "\ <(([0-9] | [1-9] [0-9] | 1 [0-9] {2} | 2 [0-4] [0-9] | 25 [0-5]) \.) { 3} ([0-9] | [1-9] [0-9] | 1 [0-9] {2} | 2 [0-4] [0-9] | 25 [0-5]) \ > "
[$? -eq 0] || (echo "input error"; exit 10)
IP = `echo $ net | egrep -o" ^ ([0-9] {1,3} \.) {3} "`
for i in {1..254}; do
        {
        ping -c 1 -w 1 $ IP $ i &> / dev / null && \
        echo "$ IP $ i is up"
        } &

done
wait
 Analysis: Please enter an IP address example 192.168.37.234, if the format is not 0.0.0.0, then report an error and exit; if it is correct, enter the loop, the value of the IP variable is 192.168.37. The range of i is 1-254, parallel ping 192.168.37.1- 154, ping will output this IP as UP. Until the end of the cycle.

 

4. Signal capture trap 1. Usage format trap 'trigger command' signal, after the custom process receives the specified signal sent by the system, it will execute the trigger command instead of the original operation trap ”signal, and ignore the signal operation trap” -'Signal, restore the original signal operation trap -p, list the custom signal operation signal can be expressed in 3 ways: signal number 2, full name SIGINT, abbreviation INT 2, commonly used signals: 1) SIGHUP: without closing the process without Let it reread the configuration file 2) SIGINT: abort the running process; equivalent to Ctrl + c 3) SIGQUIT: equivalent to ctrl + \ 9) SIGKILL: force to kill the running process 15) SIGTERM: terminate the running process (default 15) 18) SIGCONT: continue to run 19) SIGSTOP: background sleep 9 signal, forced to kill, unable to capture 3. Case: ① print 0-9, ctrl + c cannot be terminated
#! / bin / bash
trap 'echo press ctrl + c' 2
for ((i = 0; i <10; i ++)); do
        sleep 1
        echo $ i
done
 Analysis: i = 0, when i <10, every 1 second of sleep, i + 1, capture 2 signals, and execute echo press ctrl + c

 
② Print 0-3, ctrl + c can not be terminated, resume after 3, can be terminated

#! / bin / bash
trap '' 2
trap -p
for ((i = 0; i <3; i ++)); do
        sleep 1
        echo $ i
done
trap '-' SIGINT
for ((i = 3; i <10; i ++)); do
        sleep 1
        echo $ i
done
 Analysis: i = 0, when i <3, every 1 second of sleep, i + 1, capture 2 signal; when i> 3, release capture 2 signal.

 

5. Script knowledge (continuously updated)

1. Generate random characters cat / dev / urandom Generate 8 random capital letters or numbers cat / dev / urandom | tr -dc [: alnum:] | head -c 8 2. Generate random numbers echo $ RANDOM Determine the range echo $ [RANDOM% 7] Random 7 numbers (0-6) echo $ [$ [RANDOM% 7] +31] Random 7 numbers (31-37) 3. echo print color word echo -e "\ 033 [31malong \ 033 [0m "show red along echo -e" \ 033 [1; 31malong \ 033 [0m "highlight red show echo -e" \ 033 [41malong \ 033 [0m "show red echo echo with background color "\ 033 [31; 5malong \ 033 [0m" display flashing red along color = $ [$ [RANDOM% 7] +31] echo -ne "\ 033 [1; $ {color}; 5m * \ 033 [0m "Display flashing random color along
 

Six, share a few interesting small scripts

1, 9x9 multiplication table
#! / bin / bash
for a in {1..9}; do
        for b in `seq 1 $ a`; do
                let c = $ a * $ b; echo -e "$ {a} x $ {b} = $ c \ t \ c"
        done
        echo
done
 

 

2. Colored isosceles triangle

#! / bin / bash
read -p "Please input a num:" num
if [[$ num = ~ [^ 0-9]]]; then
        echo "input error"
else
        for i in `seq 1 $ num`; do
                xing = $ [2 * $ i-1]
                for j in `seq 1 $ [$ num- $ i]`; do
                        echo -ne ""
                done
                for k in `seq 1 $ xing`; do
                        color = $ [$ [RANDOM% 7] +31]
                        echo -ne "\ 033 [1; $ {color}; 5m * \ 033 [0m"
                done
                echo
        done
fi
 

3. Chess board

#! / bin / bash
red = "\ 033 [1; 41m \ 033 [0m"
yellow = "\ 033 [1; 43m \ 033 [0m"

for i in {1..8}; do
        if [$ [i% 2] -eq 0]; then
                for i in {1..4}; do
                        echo -e -n "$ red $ yellow";
                done
                echo
        else
                for i in {1..4}; do
                        echo -e -n "$ yellow $ red";
                done
                echo
        fi
done
 
 

 Well, today's content is here, in fact, the script skills of Xiaobian are also small white levels. Everyone works together to strive for advanced scripting gods! ! !

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.