For/while loop commands in shell programming

Source: Internet
Author: User

One, for command

In shell programming, sometimes we need to repeat the command until a certain condition is reached, and the bash shell provides a for command that allows you to create a loop that iterates through a series of values, each of which executes a set of predefined commands through a value in that series.

For basic format:

for Var in list

Do

Commands

Done

In the list, you provide a series of values to be used in the iteration. In each iteration, the variable var contains the current value in the list, the first iteration applies to the first value in the list, the second value is used by the second iteration, and so on, until all the values in the list pass through.


1.1 reading the values in the list

[[email protected] shell]# Cat for1.sh#!/bin/bashfor Test in AAA BBB CCC Ddddo echo the next state is $testdone [[em AIL protected] shell]# sh for1.sh the next state was aaathe next state was bbbthe next state was cccthe next state was DDD

The value of the $test variable remains in effect for the last iteration of the shell script, unless you modify it

[email protected] shell]# cat for1.sh #!/bin/bashfor test in AAA BBB CCC Ddddoecho The next state is $testdoneecho "the L AST state we visited was $test "Test=fffecho" wait.  Now we ' re visiting $test "[[E-mail protected] shell]# sh for1.sh the next state was aaathe next state was bbbthe next state is Cccthe next state are dddthe last state we visited was dddwait. Now we ' re visiting FFF


1.2 Reading complex values from a list

In the shell script, the advantage you will encounter is the number of difficult to handle. Here's a classic example of a problem for Shell scripting programmers:

[[email protected] shell]# cat for2.sh #!/bin/bashfor test in I don ' t know if this ' ll Workdoecho "word: $test" Done[[email p Rotected] shell]# sh for2.sh word:Iword:dont know if thisllword:work

Workaround: Use escape characters or double quotation marks

[[email protected] shell]# cat for2.sh #!/bin/bashfor test in I don\ ' t know if "this ' ll" Workdoecho "Word: $test" Done[[emai L protected] shell]# sh for2.sh word:Iword:don ' tword:knowword:ifword:this ' llword:work


Remember that the For loop assumes that each value is separated by a space, and if there are spaces in a separate numeric value, you must use double quotation marks to enclose the values.



1.3 Reading a list from a variable

[[email protected] shell]# cat for3.sh #############################!/bin/bashlist= "AAA BBB CCC ddd Eee" list= $list " Connecticut "for $listdo echo" has you ever visited $state "Done[[email protected] shell]# sh for3.sh has you ev  Er visited aaahave you ever visited Bbbhave are ever visited Ccchave you ever visited Dddhave you ever visited EeeHave Ever visited Connecticut


1.4 reading a value from a command

[email protected] shell]# cat for4.sh #!/bin/bashfile= "/root/shell/states" #如果是在当前不用绝对路径, file= "states" Cat $file ' do echo ' Visit beautiful $state "done[[email protected] shell]# sh for4.sh Visit beautiful shanghaivisit beautif UL beijingvisit beautiful hangzhouvisit beautiful nanjingvisit beautiful guangzhou[[email protected] shell]# cat states SH Anghaibeijinghangzhounanjingguangzhou

1.5 changing field separators

    • Spaces

    • Tabs:

    • Line break


If the bash shell sees any of these characters in the data, it assumes that you have started a new data segment in the list.

To solve this problem, you can temporarily change the value of the IFS environment variable in your shell script to limit the characters that are treated as field separators by the bash shell. But this is a bit odd, for example, if you line the value of IFS so that it recognizes only line breaks, you must do this:

ifs=$ ' \ n '

Add this statement to the script and tell the bash shell to ignore spaces and tabs in the data values.

[email protected] shell]# cat for5.sh #!/bin/bashfile= "states" ifs=$ ' \ n ' for the state ' cat $file ' do echo ' Visit beautiful $state "Done[[email protected] shell]# sh for5.sh Visit beautiful shanghaivisit beautiful beijingvisit beautiful Hangzhouv Isit beautiful nanjingvisit Beautiful guang zhouvisit beautiful nan ningvisit beautiful Jiang Nan

In a long script, you might need to modify the value of IFS in one place, and then forget that it restores the default values elsewhere in the script.

For example:

Ifs. Old= $IFS

ifs=$ ' \ n '

<use the new IFS value in code>

Ifs= $IFS. Old


Other IFS values, such as: May be used in/etc/passwd

Ifs=:

You can also assign multiple IFS:

Ifs=$ ' \ n:; "'


1.6 reading a directory with wildcard characters

[[email protected] shell]# cat for6.sh #!/bin/ bashfor file in /home/*do  if [ -d  "$file"  ];thenecho  "$file  is a directory   elif [ -f  $file  ];thenecho  $file   Is a file "  fidone[[email protected] shell]# sh for6.sh /home/ Apache-tomcat-8.0.28.tar.gz is a file/home/dir1 is a directory/home/dir2 is  a directory/home/fie1 is a file/home/fie2 is a file/home/fie22  Is a file 
[email protected] shell]# cat for7.sh #!/bin/bashfor file in/home/*/home/badtestdo if [-D "$file"];thenecho "$file I S a directory "elif [-F" $file "];thenecho" $file is a file "Elseecho" $file doesn ' t exist "fidone[[email protected] s hell]# SH for7.sh/home/apache-tomcat-8.0.28.tar.gz is a file/home/dir1 are a directory/home/dir2 is a directory/home/fie1 is a file/home/fie2 are a file/home/fie22 is a file/home/badtest doesn ' t exist


Second, C language style for command

2.1 C language-style for command

The for command of the C language has a special method to indicate the variable, a condition that must remain in order to continue iterating, and another method for changing the variable for each iteration. The For loop stops when the specified condition is not true. The conditional equation is defined by a standard number symbol.

for (i=0; i<10; i++)

{

printf ("The next number is%d\n", i):

}

The first part assigns a default value to the variable, the middle part defines the condition of the recurrence, and when the defined condition is not true, the for loop stops iterating, and the last part defines the process of the iteration.


The basic format for the C-style for loop in bash:

for ((variable assignment;condition;iteration process))

for ((a = 1; a <; a++))


[email protected] shell]# cat c1.sh #!/bin/bashfor ((i=1; i <; i++)) do echo "The next number is $i" Done[[email p  Rotected] shell]# sh c1.sh The next number is 1The next number was 2The next number is 3The Next number is 4The next number Is 5The next number was 6The next number is 7The next number was 8The next number is 9


2.2 Using multiple variables

The C language-style for command also allows you to use multiple variables for the iteration. Loops process each variable individually, allowing you to define different iterations for each variable. When you have multiple variables, you can only define a condition in the For loop:

[[email protected] shell]# cat c2.sh #!/bin/bashfor ((A=1, b=10; a <=; a++, b--)) do echo "$a-$b" Done[[email Pro Tected] shell]# sh c2.sh 1-102-93-84-75-66-57-48-39-210-1

Third, while command

The while command is in a sense a mixture of the If-then statement and the For loop. The while command allows you to define a command to test, and then loop through a set of commands, as long as the defined test command returns exit status code 0, it tests the test command at the beginning of each iteration, and the test command returns a non-0 exit status code, the while command stops executing that set of commands.

Basic format for 3.1while

While Test command

Do

Other command

Done


The exit status code of the test command specified by the while command must change with the command running in the loop, and if the exit status code does not change, then the while loop will continue to loop continuously.

[[email protected] shell]# cat w1.sh #!/bin/bashvar1=10while [$var 1-gt 0]do echo $var 1 var1=$[$var 1-1]done[[email Protected] shell]# sh w1.sh 10987654321

In these commands, the variables used in the test conditions must be modified, or you will enter an infinite loop.


3.2 Using multiple test commands

The while command allows you to define multiple test commands on the while statement line, and only the exit status code of the last Test command is used to determine when the loop is introduced.

[email protected] shell]# cat w2.sh #!/bin/bashvar1=10while echo $var 1[$var 1-ge 0]do echo "This is inside the loop" var1=$[$var 1-1]done[[email protected] shell]# sh w2.sh 10This is inside the loop9this are inside the loop8this is Insid E The loop7this is inside the loop6this are inside the loop5this is inside the loop4this are inside the loop3this is inside The loop2this is inside the loop1this are inside the loop0this is inside the loop-1

In the example above, two test commands are defined in the while statement:

While Echo $var 1

[$var 1-ge 0]


In the while statement, all of the test commands are executed in each iteration, including the last loop that the last command was not formed. Note that each test command is on a separate line.




For/while loop commands in shell 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.