Shell from getting started to giving up (bottom)

Source: Internet
Author: User

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M02/80/20/wKiom1c4dD-wFZx7AAAbgLBZiMU936.jpg "title=" Wkiol1cwdpjb1fbhaaabfqyv8vs885.jpg "alt=" Wkiom1c4dd-wfzx7aaabglbzimu936.jpg "/>



First, the great cycle of the For loop

Similar to other programming languages, the shell supports A for loop.

For loop General format: For variable in list do Command1 Command2 ... commandndone

A list is a sequence of values (numbers, strings, and so on), each separated by a space. Each time the loop is passed, the next value in the list is assigned to the variable.

The in list is optional, if it is not used, the For loop uses the command-line positional parameters.

For example, sequentially output the numbers in the current list:

For loop in 1 2 3 4 5 does echo "The value is: $loop" done


Operation Result:

The value is:1the value is:2the value is:3the value is:4the value is:5


Characters in the sequential output string:

For STR in ' The A string ' do echo $strdone

Operation Result:

This is a string


Show files starting with. Bash in the home directory:

#!/bin/bashfor FILE in $HOME/.bash*do echo $FILEdone


Operation Result:

/root/.bash_history/root/.bash_logout/root/.bash_profile/root/.bashrc


Second, the great cycle of the while loop


The while loop is used to continuously execute a series of commands and to read data from the input file; the command is usually a test condition. The format is:

While Commanddo Statement (s) to being executed if command is Truedone

The command finishes, control returns to the top of the loop, and starts from the beginning until the test condition is false.

The following is a basic while loop, and the test condition is: Returns True if counter is less than 5. Counter starting from 0, counter plus 1 for each cycle of processing. Run the above script, return the number 1 to 5, and then terminate.

Counter=0while [$COUNTER-lt 5]do counter= ' expr $COUNTER +1 ' echo $COUNTERdone

Run script, Output:

12345

The while loop can be used to read keyboard information. In the following example, the input information is set to the variable film, ending the loop by <Ctrl-D>.

echo ' type <CTRL-D> to terminate ' echo-n ' Enter your most liked film: ' while read Filmdo echo ' yeah! Great film The $FILM "done

Run the script with the output similar to the following:

Type <CTRL-D> to terminateenter your most liked film:sound of musicyeah! Great film The Sound of Music


Three, the great cycle of the until cycle


The Until loop executes a series of commands until the condition is true. The Until loop and the while loop are just the opposite of the processing mode. The general while loop is better than the until loop, but at some point it is only rare that the until loop is more useful.

Until loop format: until Commanddo Statement (s) to being executed until command is Truedone

The command is usually a conditional expression, and if the return value is false, the statement in the loop body continues to execute, otherwise it jumps out of the loop.

For example, use the until command to output a number from 0 to 9:

#!/bin/basha=0until [! $a-lt]do echo $a a= ' expr $a + 1 ' done

Operation Result:

0123456789


Four, I want to leave you out of the loop

In the loop, sometimes you need to force out of the loop when the loop end condition is not reached, like most programming languages, the shell also uses break and continue to jump out of the loop.

Break command

The break command allows you to jump out of all loops (all loops after the execution is terminated).

In the following example, the script enters a dead loop until the user enters a number greater than 5. To jump out of this loop and return to the shell prompt, use the break command.

#!/bin/bashwhile:d o echo-n "Input a number between 1 to 5:" Read Anum case $aNum in 1|2|3|4|5) echo "Yo    ur number is $aNum! ";    *) echo "You don't select a number between 1 to 5, game is over!"    break;; Esacdone

In a nested loop, the break command can also be followed by an integer that indicates a loop that jumps out of the first layer. For example:

Break n

Indicates a jump out of the nth layer loop.

Here is an example of a nested loop, if Var1 equals 2, and var2 equals 0, jump out of the loop:

#!/bin/bashfor var1 in 1 2 3do for VAR2 in 0 5 does if [$var 1-eq 2-a $var 2-eq 0] then break 2 Else echo "$var 1 $var 2" fi donedone

As above, break 2 means to jump out of the outer loop directly. Operation Result:

1 01 5


Continue command

The continue command is similar to the break command, with only a little difference, and it does not jump out of all loops and just jumps out of the current loop.

To modify the above example:

#!/bin/bashwhile:d o echo-n "Input a number between 1 to 5:" Read Anum case $aNum in 1|2|3|4|5) echo "Yo        ur number is $aNum! ";            *) echo "You don't select a number between 1 to 5!"        Continue echo "Game is over!"    ;; Esacdone


Running code discovery, when you enter a number greater than 5, the loop in this example does not end, and the statement

echo "Game is over!"


Will never be executed.

Similarly, the continue can be followed by a number, indicating that the first layer jumps out of the loop.

Let's look at a continue example:

#!/bin/bashnums= "1 2 3 4 5 6 7" for NUM in $NUMSdo q= ' expr $NUM% 2 ' if [$Q-eq 0] then echo "Number is a        N Even number!! " Continue fi echo "Found odd number" done

Operation Result:

Found Odd Numbernumber is an even number!! Found Odd Numbernumber is an even number!! Found Odd Numbernumber is an even number!! Found Odd number


V. The function of my site listen to me.

function allows us to divide a complex function into several modules, which makes the program structure clearer and the code reuse more efficient. Like other programming languages, the Shell supports functions as well. The Shell function must be defined before use.

The Shell functions are defined in the following format:

Function_name () {List of commands [return value]}

If you prefer, you can also add keyword functions to the function name:

function function_name () {List of commands [return value]}

function return value, you can explicitly increment the return statement, if not added, the last command will run the result as the return value.

The Shell function return value can only be an integer, which is generally used to indicate success or failure of the function, 0 for success, and other values to fail. If you return other data, such as a string, you will often get an error message: "Numeric argument required".

If you have to make the function return a string, you can first define a variable to receive the result of the function, and the script accesses the variable when needed to get the function return value.

Let's look at an example:

#!/bin/bash# Define your function Herehello () {echo "URL is http://zhaoyongtao.blog.51cto.com/"}# Invoke your Functio Nhello

Operation Result:

$./test.shhello world$

The calling function only needs to give the function name, and no parentheses are required.

Then look at a function with a return statement:

#!/bin/bashfunwithreturn () {echo "The function is to get the sum of the numbers ..." echo-n "Input first Number:"    Read Anum echo-n "Input Another number:" Read Anothernum echo "The numbers is $aNum and $anotherNum!" Return $ (($aNum + $anotherNum))}funwithreturn# Capture value returnd by last Commandret=$?echo "The sum of the numbers are $ret! "


Operation Result:

The function is to get the sum of the numbers ... Input first Number:25input Another number:50the, numbers are and 50! The sum of numbers is 75!

function return value after calling this function through $? To obtain.

Let's look at an example of a function nesting:

#!/bin/bash# calling one function from Anothernumber_one () {echo ' url_1 is http://zhaoyongtao.blog.51cto.com/' Numbe R_two}number_two () {echo "url_2 is http://zhaoyongtao.blog.51cto.com/10955972/1773727"}number_one


Operation Result:

Url_1 is http://zhaoyongtao.blog.51cto.com/Url_2 is http://zhaoyongtao.blog.51cto.com/10955972/1773727

As with the delete variable, the delete function can also use the unset command, but add the. f option as follows:

$unset. F function_name


If you want to invoke the function directly from the terminal, you can define the function in the. profile file in the home directory so that you can call it immediately after each login by entering the function name at the command prompt.


Shell function Parameters

In the shell, arguments can be passed to a function when it is called. Inside the function body, the value of the parameter is obtained in the form of a $n, for example, $ $ for the first argument, and $ = for the second argument ...

Examples of functions with parameters:

#!/bin/bashfunwithparam () {    echo  "the value of the first  parameter is $1 ! "     echo  "the value of the second parameter is $2  ! "     echo  "the value of the tenth parameter is $10  ! "     echo  "the value of the tenth parameter is ${10 } ! "     echo  "the value of the eleventh parameter is $ {11} ! "     echo  "the amount of the parameters is $# !"   #  Number of parameters     echo  "The string of the parameters  is $* ! "   #  all parameters passed to the function}funwithparam 1 2 3 4 5 6 7 8 9  34 73


To run the script:

The value of the first parameter is 1! The value of the second parameter is 2! The value of the tenth parameter is 10! The value of the tenth parameter is 34! The value of the eleventh parameter is 73! The amount of the parameters is 12! The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73! "

Note that the $ $ cannot get the tenth parameter, and the tenth parameter requires ${10}. When n>=10, you need to use ${n} to get the parameters.

In addition, there are several special variables to handle the parameters, as mentioned earlier:

Special Variables Description
$# The number of arguments passed to the function.
$* Displays all arguments passed to the function.
[Email protected] Same as $*, but slightly different, see Shell special variables.
$? The return value of the function.


The Shell file contains

Like other languages, the Shell can also contain external scripts that merge the contents of the external script into the current script.

The Shell contains scripts that can be used:

. FileName

Or

SOURCE filename

The effect of the two methods is the same, for simplicity, the dot (.) is generally used, but note the dot (.) There is a space in the middle of the file name.

For example, create two scripts, one called Script subscript.sh, with the following:

Url= "http://zhaoyongtao.blog.51cto.com/10955972/1773727"

One is the main file main.sh, which reads as follows:

#!/bin/bash. /subscript.shecho $url

Execute script:

$CHOMD +x main.sh./main.shhttp://zhaoyongtao.blog.51cto.com/10955972/1773727

Note: The included scripts do not need to have execute permissions.


Shell script part of the first temporary, the shortcomings also hope to point out.

This article from the "mood refined, quiet Zhiyuan" blog, please be sure to keep this source http://zhaoyongtao.blog.51cto.com/10955972/1773727

Shell from getting started to giving up (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.