Shell Scripting Basics (bottom)

Source: Internet
Author: User

Case judgment in the shell

Format: Case variable name in

value1)

Command

;;

value2)

Command

;;

*)

Commond

;;

Esac


In a case program, you can use a |, meaning, or means in a condition, such as:

2|3)

Command

;;

When the variable is 2 or 3 o'clock, the part of the command is executed.


Application Examples:

[[email protected] shell]# cat test7.sh #!/bin/bashread -p  "Please enter student's score:  " numn1= ' echo  $num  | sed  ' s/[0-9]//g '           //to determine if the digital if [ ! -z  $n 1 ]then    echo  " This is not a number. Please Enter!! " exit 1 fiif  [[  $num  -gt 100 | |   $num  -lt 0 ]]then    echo   Student's score is 0-100, please enter it again! "exit 1elif [  $num  -ge 90 ] && [  $num  -le 100  ]then     tag=1elif [  $num  -ge 80 ] &&  [  $num  -le 90 ]then    tag=2elif [  $num  -ge  70 ] && [  $num  -le 80 ]then    tag=3elif [   $num  -ge 60 ] && [  $num -le 70 ]then    tag=4else     tag=5ficase $ TAG IN     1)  echo  "Excellent! ";;      2)  echo  "Good! ";;      3) echo  "Medium! ";;      4) echo  "Hooray! Pass It! ";;      5) echo  "Sorry! You didn't pass! We need a retake! ";; esac[[email protected] shell]# sh test7.sh  Please enter student's score:  111 Student's score is 0-100, please enter again! [[email protected] shell]# sh test7.sh  Please enter student's score:  dagfag This is not a number please enter it again!! [[email protected] shell]# sh test7.sh  Please enter student's score:  89 good!

Using the example above can see the use of case judgment, although the example is not very good, but a more comprehensive practice of if and case statements, when writing due to their own sloppy in the judgment sentence if [!-Z $n 1] in the-Z less write-led to the error, please everyone warning!


Viii. loops in shell scripts

1. For loop

Syntax structure: For variable name in condition; do ... done;


Application Examples:

[[email protected] shell]# cat test8.sh #!/bin/bashread-p "Please enter a number:" Nn1= ' echo $n |       Sed ' s/[0-9]//g ' if [!-Z $n 1]then echo "Please enter a number!" Exit 1fisum=0for i in ' seq 1 $n ' does sum=$ (($i + $sum)) done Echo $sum
[[Email protected] shell]# sh test8.sh-x Please enter a number: 1055[[email protected] shell]# sh test8.sh-x Please enter a number: 999499500[[email PR Otected] shell]# sh test8.sh-x Please enter a number: 999994999950000[[email protected] shell]# sh test8.sh- x Please enter a number: 564575715937288874403

The example above is to manually enter a number to calculate its sum from 0 to itself and the output, in addition to the last number of CPU operation for more than 20 seconds, so it's OK not to play like this.


2. While loop

Grammatical structure: while condition; Do ... done dead loop with: expression;

Break directly ends this layer loop; Continue ignores the code under continue, and makes the next loop directly;

Exit directly out of the shell;


Application Examples:

[email protected] shell]# cat test9.sh #/bin/bashwhile:d o load= ' w|awk-f ' load average: ' {print$2} ' |cut-d.-f1 ' P Rocessor= ' Cat/proc/cpuinfo | grep ' Processor ' | Wc-l ' If [$load-lt $processor]//note in order to be able to receive mail I write less than, in long use is greater than then top-bn1|mail-s "load are high: $load" XX XX@126.com Else exit 0 fisleep 30done

The above example is a simple to determine whether the server is overloaded, if the overload will send information to 126 mailboxes, and is 30 seconds a letter, this example is a simple script to monitor the load of the system, to better monitor or recommend the use of professional monitoring software Cacti/nagios/zabbix and other tools.


[email protected] shell]# cat test9.sh #/bin/bashwhile:d o load= ' w|awk-f ' load average: ' {print$2} ' |cut-d.-f1 ' P Rocessor= ' Cat/proc/cpuinfo | grep ' Processor ' | Wc-l ' If [$load-lt $processor]//note in order to be able to receive mail I write less than, in long use is greater than then top-bn1|mail-s "load are high: $load" XX XX@126.com Else exit 0 fisleep 30done

The above example is a simple introduction to the difference between using the same continue and break out loops in a while statement, simply speaking:

Break: ends and exits the loop.

Continue: The following code is not executed in the loop and continue into the next round loop

exit: exit the script, always bring an integer to the system, such as Exit 0

return: returns the data in the function, or a script that returns a result to the calling function


Nine, Shell function

1. Introduction to Shell functions

A very important feature of the shell is that it can be used as a programming language. Because the shell is an interpreter, it cannot compile the programs written for it, but instead interprets them every time they are loaded from disk. and the loading and interpretation of the program is very time-consuming. For this issue, many shells, such as Bourneagainshell, contain shell functions that the shell puts in memory so that they do not have to be read from the disk each time they need to be executed. The shell also stores these functions in an internal format, so that you don't have to spend a lot of time explaining them.


2. Shell function syntax

The function consists of two parts: the function title and the function body.

The title is the function name. A function body is a collection of commands within a function. The title name should be unique, and if not, the result will be confused because the script will first search for the function to call the corresponding S H e l L before looking at the calling script.

The format of the definition function is:

Function name ()

{

Command 1

. . .

}

Or

Function name () {

Command 1

. . .

}

Both ways are feasible. If you prefer, you can precede the function name with the keyword f u n c t i o n, depending on the user.

f u n c t i o n function name ()

{ ...

}

You can consider a function as a piece of code in a script, but there is one major difference. When the function is executed, it retains the current s H e L and memory information. In addition, if you execute or invoke another piece of code in a script file, a separate s h e l l will be created, thus removing any existing variables defined in the original script. functions can be placed in the same file as a piece of code, or in a separate file containing only functions. The function does not have to contain many statements or commands, or even a single e c h o statement, depending on the consumer. parameters returned, can be displayed plus: return returns, if not added, will run the result as the last command, as the return value. return followed by value N (0-255)


3. Shell Function Application Example

Check the function of the IP address, enter a network card name, and output the IP address of the network card;

[[email protected] shell]# cat fun1.sh #/bin/bashread -p  "Please enter the network card:"   networkip  ()  {     ifconfig  $network |head -2|tail -1|awk  -F  ': '   ' {print$2} ' |awk  ' {print$1} '}case  $network  in    eth* )         echo  "This is the Ethernet NIC,"          ipaddr= ' ip  $network '         echo  ' $network IP is: $ IPAddr "        ;;       lo)         echo  "This is the loopback network card"         ipaddr= ' ip  $network '          echo  "$network IP is: $ipaddr"         ;;        *)         echo  "You entered the incorrect, please new input!" "        ;; Esac


Extended Learning:

Select is also a kind of loop, it is more suitable for use in the case of user choice.

For example, we have one such requirement, after running the script, let the user go to select the number, select 1, run the W command, select the 2 run Top command, select 3 run the free command, select 4 to exit.

#!/bin/bashps3= "please select a number: " echo  "Please chose a number,  1: run w, 2: run top, 3: run free, 4: quit "Echoselect  command in w top free quitdo    case  $command  in     W)         w         ;;     top)         top         ;;     free)         free         ;;     quit)         exit         ;;     *)         echo  "Please input a  number: (1-4). "     esacDone 
[[Email protected] shell]# sh select1.sh please chose a number, 1 :  run w, 2: run top, 3: run free, 4: quit1)  w2)   TOP3)  free4)  quitplease select a number: 1 09:34:03 up  9:39 ,  2 users,  load average: 0.00, 0.00, 0.00user      TTY      FROM               [email protected]   IDLE   JCPU    PCPU WHATroot     pts/0    192.168.1.104     00:22    0.00s  0.25s  0.00s sh select1.shroot      pts/1    192.168.1.104    01:24    14:18    0.36s  0.36s -bashplease select a number: 4 



This article is from the "Bread" blog, make sure to keep this source http://9950284.blog.51cto.com/9940284/1666054

Shell Scripting Basics (bottom)

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.