Linux operation and Architecture-shell programming (II)

Source: Internet
Author: User
Tags array length case statement function definition pear rsync

I. Process Control statements

1. If statement

①IF Single branch: one condition one result

If condition  then     command fi

②IF Dual Branch: One condition two results

If condition  then    command Else   command 2fi

③IF Multi-Branch: Multiple conditions multiple results

If condition  then    command elif Condition 2  then    command 2elif condition 3  then    command 3......else   command 4fi

#企业面试题001 #

Development of Detection system memory monitoring script, if less than 800M, mail alarm, and scheduled tasks every three minutes to perform a test

cat check_mem.sh#!/bin/shmem'nr==3{print $NF}'if " $Mem " "  - " ]  then    echo $Mem" system memory less than 800M"774181401@ Qq.comfi

#企业面试题002 #

Simulate the startup Nginx script, using the IF statement to determine if the input is start, stop, restart ...

#!/bin/Sh./etc/init.d/Functionsnginx_start="/application/nginx/sbin/nginx"Nginx_stop="${nginx_start}-S Stop"if[" $"=="Start"] then ${nginx_start} action"starting Nginx"/bin/trueElif [" $"=="Stop"] then ${nginx_stop} pkill Nginx Action"Nginx is stopped"/bin/trueElif [" $"=="Restart"] then ${nginx_stop}&&${nginx_start} action"Nginx is restarting"/bin/trueElif [" $"!="Start"-A" $"!="Stop"-A" $"!="Restart"] Echo"USAGE: $ {Start|stop|restart}"fi

2. Case statement

① syntax

Case $x in value 1)   command 1   ;; Value 2)   command 2   ;; Value 3)   command 3   ;; *)   Command 4esac

The ②case statement is equivalent to a multi-branch if statement, suitable for fewer variables, and a fixed number or set of strings, more for system startup scripts

#case实战菜单小题 #

#!/bin/Bashcat<<EOF1. Install rsync2. Install NFS3. Install MySQL4. Install All5. Exiteofread-P'Please enter your choice:'Num Case$numinch  1) echo"Install rsync suscess!"   ;; 2) echo"Install NFS suscess!"   ;; 3) echo"install MySQL suscess!"   ;; 4) echo"Install all suscess!"   ;; 5) exit;; *) echo"Wrong Choice"Esac

#case结合while实战水果菜单选择 #

#!/bin/ShRED='\e[1;31m'GREEN='\e[1;32m'YELLOW='\e[1;33m'RES='\e[0m'Cat<<EOF==================1. Apple2. Pear3. Banana4. Exit==================EOF while true DoRead-P"Please enter the fruit you like to eat:"Choice Case$choiceinch  1) echo-E"the fruit you like is: $RED Apple $RES"    ;; 2) echo-E"the fruit you like is: $GREEN pear $RES"    ;; 3) echo-E"the fruit you like is: $YELLOW Banana $RES"    ;; 4) exit;; *) echo"wrong input"Esacdone

#给输出字体加颜色 #

Foreground color:
Echo-e "\033[30m black word oldboy trainning \033[0m" echo-e "\033[31m red word oldboy trainning \033[0m" echo-e "\033[32m green word oldboy tr Ainning \033[0m "echo-e" \033[33m yellow word oldboy trainning \033[0m "echo-e" \033[34m blue word oldboy trainning \033[0m "Echo-e" \033[ 35m purple word Oldboy trainning \033[0m "Echo-e" \033[36m sky blue word oldboy trainning \033[0m "echo-e" \033[37m white word oldboy trainning \033[0 M "Background color: echo-e" \033[40;37m Black Bottom White Welcome to old1boy\033[0m "ECHO-E" \033[41;37m Red bottom white Welcome to old2boy\033[0m "ECHO-E" 33[42;37m Green Bottom White Welcome to old3boy\033[0m "ECHO-E" \033[43;37m yellow bottom white Welcome to old4boy\033[0m "ECHO-E" \033[44;37m Blue bottom white wel Come to old5boy\033[0m "echo-e" \033[45;37m purple bottom white Welcome to old6boy\033[0m "Echo-e" \033[46;37m Sky White Welcome to OLD7BOY\03 3[0m "ECHO-E" \033[47;30m black Word Welcome to old8boy\033[0m "Off color \033[0m

3. For statement

① syntax

For i (variable) in {1..10} in the  following can be added command ' ls '  seq ' do     echo $idone

② optimized boot-up via for loop

#!/bin/shclose_service3'{print $}'"crond| Network|sshd|rsyslog|sysstat"' for in $Close _service  Do   chkconfig $name offdone

4. While statement

① syntax

While condition    do command done conditions always set--dead loop daemon: not stopped process true

②while How to read a file by line

mode one,<filesum=0 while the readline does     cmddone mode two , Cat ${file_path}|  while Read Line  Do       cmddone Way three ,while the  readline does       Cmddone <file

③ ways to prevent script interrupts

1, SH while.sh &2, nohup/server/scripts/uptime.sh &3, screen, keep the conversation

5. Functions

① syntax

#!/bin/basholdboy () {    echo "Hello World"}

Note: Oldboy is defined as a function that executes without parentheses, and the function definition and function body must be defined before the name of the function to be executed

function execution method of ② with parameters

Positional parameters in the function body ($, $, $3...$#, $*, and [email protected]) can all be parameters of the function. The parameters of the parent script are temporarily obscured or hidden by the function arguments. $ More special, he is still the name of the parent script. When the function is complete, the original command-line arguments are restored
#!/bin/bashfunction oldboyedu () {echo"Hello World"echo $0echo $1echo $2Exit}etiantian () {echo"Good"    return 3Echo' Bad'} #oldboyedu hanshu1 hanshu2oldboyedu $1$2Etiantian

③ How to write a good function script

#分层 # Each step can be written as a function # each function is split into a function

④ function Advantages

You can reduce the amount of program code by defining the same program segment as a function.
To increase the readability and legibility of the program.
The function of the realization program is modularized.

6. Shell Array

X= (1 2 3) # Print all array contents [[email protected] scripts]# echo ${x[*]}1 2 3# print array elements [[email protected] scripts]# echo ${x[0]}1[[email Protected] scripts]# echo ${x[1]}2[[email protected] scripts]# echo ${x[2]}3# print array length [[email protected] scripts]# echo ${#x [@]} 3[[email protected] scripts]# echo ${#x [*]}3

Second, the individual statement application scenario

if (value judgment)

for (normal loop processing) statements are most commonly used,

while (daemon infinite loop, tasks less than 1 minutes can be used while loop)

Case (System service startup script)

Third, Shell script debugging

① remember to first format the script with Dos2unix.
② directly executes the script according to the error to debug, sometimes inaccurate error.
③sh-x Debug the entire script, showing the execution process.
④set-x and set +x Debug section scripts (set in script)
⑤echo output variables and related content, and then immediately following exit exit, do not execute the way behind the program, step-by-step tracking script, for logic error is better.
Writing: Echo $var; exit
⑥ the most critical is the grammar proficiency, coding habits, programming ideas, to kill the mistakes in the bud, reduce the burden of debugging, improve efficiency

Linux operation and Architecture-shell programming (II)

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.