Shell programming in Linux: for Loop statement, linuxshell

Source: Internet
Author: User

Shell programming in Linux: for Loop statement, linuxshell

For Loop statements for shell programming in Linux.

1. The for loop statement is similar to the while LOOP, but the for loop is mainly used for a loop with a limited number of executions, rather than a daemon process and an infinite loop. the syntax of the for Loop is as follows:

For variable name in variable value list do Command done

In this for loop syntax, there is a variable name after the for keyword, and the variable name will obtain the Value List of the variable after in sequence, every time you take one and then loop between do and done, that is, the command. Then, loop the Value List of the next variable again and execute the do done part until the last value of the Value List of the variable enters the loop body.

 

2. The second syntax is the c-language for loop statement as follows:

For (exp1; exp2; exp3) do Command done

Example 1:

for ((a=1;a<=10;a++))doecho $adone

The output result is as follows:

[root@yankerp shell]# sh for_check.sh 12345678910[root@yankerp shell]# 

Analysis:

For (a = 1; a <= 10; a ++ )) # a = 1 then a is 1 a <= 10 then 1 <10 but not 10 so after a ++ Add 1 doecho $ a # The first Input $ a is 1 then the second a ++ is equal to a + 1, that is, 1 + 1. The second output is 2 until a = 10 done # ends.

The preceding for loop is similar to the while statement as follows:

a=1while ((a<=10))doecho $a((a++))done

The output result is as follows:

[root@yankerp shell]# sh while.sh 12345678910[root@yankerp shell]#

If you want the program to run continuously, the while loop is the best choice.

If it is a limit loop, use the for loop !!!

 

3. Basic for loop practice

Example 1: Use a for loop to print 1 2 3 4 5 numbers as follows:

#!/bin/bashfor zhangsan in 1 2 3 4 5do        echo $zhangsandone

The analysis is as follows:

There will be a variable name behind the for keyword. The variable name will get the content of the variable value list after in sequence. Each time we take one and then loop between do and done, that is, the instruction. Then, loop the Value List of the next variable again and execute the do done part until the last value of the Value List of the variable enters the loop body.

Final output content:

[root@yankerp shell]# sh for_check.sh 12345[root@yankerp shell]# 

 

Example 2: Use {} to print 1 2 3 4 5

I have mentioned {} in the previous articles, for example, printing 1-15 or a-z.

[root@yankerp shell]# echo {1..15} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15[root@yankerp shell]# echo {a..z} a b c d e f g h i j k l m n o p q r s t u v w x y z[root@yankerp shell]# 

Combine {} loops with for Loops

[Root @ yankerp shell] # cat for_check.sh #! /Bin/bashfor zhangsan in {1 .. 5} # Or {.. z} do echo $ zhangsandone [root @ yankerp shell] # sh for_check.sh 12345 [root @ yankerp shell] #

Output a-z

[root@yankerp shell]# sh for_check.sh abcdefghijklmnopqrstuvwxyz[root@yankerp shell]# 

 

Instance 3: Modify the file Suffix in batches

We can see that there are so many files in this directory, but their suffixes are different, but the requirement is that I want to change all files in txt format. the first method of sh is changed manually. The second method is as follows:

1. First, we need to change the suffix. First, we need to define a variable for testing.

[root@yankerp data]# aaa=csdn.txt[root@yankerp data]# echo $aaacsdn.txt[root@yankerp data]# echo $aaa | cut -d . -f1 csdn[root@yankerp data]# echo "`echo $aaa | cut -d . -f1`".shcsdn.sh[root@yankerp data]#

The analysis is as follows:

[Root @ yankerp data] # aaa%csdn.txt # defines a variable aaa%csdn.txt, such as aaa%csdn.txt [root @ yankerp data] # echo $ aaa ????? # Echo $ aaa is csdn.txtcsdn.txt # output result [root @ yankerp data] # echo $ aaa | cut-d. -f1 # Here we use the cut command through. csdn ???????? # The csdn captured is added after csdn. sh: [root @ yankerp data] # echo "'echo $ aaa | cut-d. -f1 '". sh ???? # Add. sh to the above command to achieve this effect. csdn. sh [root @ yankerp data] #

 

The above is a variable method, then write the for loop modification method

2. We need to change the txt suffix to the end of sh, so we must find all the files ending with the txt file in the directory as follows:

[root@yankerp data]# ls | grep txt$a.txtb.txtc.txtd.txtuuub.txt[root@yankerp data]#

At this point, I think it should be clear that the method to be modified is as follows:

#! /Bin/bashcd/root/data | {echo "failed to enter the directory !!! "Exit 1} for zhangsan in 'ls | grep txt $ 'do mv $ zhangsan' echo $ zhangsan | cut-d.-f1'. shdone

3. Analysis:

#! /Bin/bashcd/root/data | {# access to the file directory echo "failed to access the directory !!! "# Check whether the access is successful !!! Exit 1} for zhangsan in 'ls | grep txt $ '# A variable is followed by the command, that is, all files ending with txt, start loop do mv $ zhangsan 'echo $ zhangsan | cut-d. -f1 '. sh # This is the above variable command. Done

Modify as follows:

 

Example 4: Decompress files in batches as follows:

In this directory, we can see a lot of packages, but there are .tar.gz and rar and zipping packages. However, I want to decompress the .tar.gz packages. The first method is to manually decompress the packages one by one. The second method is as follows:

There are several 1.w.tar.gz packages.

2. write the script as follows:

#! /Bin/bashcd/root/data | {echo "failed to enter the directory !!! "Exit 1} for zhangsan in 'ls | grep .tar.gz $ 'do tar zxf $ zhangsan-C/root/logdoneif [" $? "-Eq 0]; then echo" .tar.gz success !!! "Else echo" failed !!! "Fi

 

The running result is as follows:

 

Instance 5: develop batch User Creation scripts

First, batch creation of users is well implemented as follows:

#! /Bin/bashNAME = yankaifor zhangsan in 'seq-w 1 5' do useradd $ NAME $ zhangsandoneif ["$? "-Eq 0]; then echo" user created successfully !!! "Else echo" failed to create user !!! "Exit 1fi

Run the following command:

But the question is, how can we add a password to a user? The user must have a password. Generally, we can set a password for a user as follows:

[Root @ yankerp ~] # Echo 123456 | passwd -- stdin zhangsan: change the password of user zhangsan. Passwd: All authentication tokens have been successfully updated. [Root @ yankerp ~] #

We can use $ RANDOM | md5sum to randomly match the password to intercept the first eight digits as follows:

Then we have some ideas to write the script as follows:

#! /Bin/bash. /etc/init. d/functionsNAME = yankaiZF = 'seq 1 10' for user in $ ZFdouseradd $ NAME $ userPASS = "'echo $ RANDOM | md5sum | cut-c 1-8'" echo "$ PASS" | passwd -- stdin $ NAME $ user &>/dev/nullecho "$ NAME $ user: $ PASS "if [" $? "-Eq 0] then action" $ NAME $ user is OK! "/Bin/true else action" $ NAME $ user not OK! "/Bin/false exit 1 fidone

Run the following command:

The analysis is as follows:

#! /Bin/bash. /etc/init. d/functions # load function library NAME = yankai # define the NAME as yankaiZF = 'seq 1 10' # Take the number 1-10 for user in $ ZF # for Loop user is the variable $ ZF value douseradd $ NAME $ user # create an yankai account and + 1 PASS = "'echo $ RANDOM | md5sum | cut-c 1-8'" # define a RANDOM password to retrieve the first 8 echo "$ PASS "| passwd -- stdin $ NAME $ user &>/dev/null # Set the user Password echo" $ NAME $ user's password: $ PASS "# output user password if [" $? "-Eq 0] # determine then action" $ NAME $ user is OK! "/Bin/true else action" $ NAME $ user not OK! "/Bin/false exit 1 fidone # The above content continues until seq 1-10 has reached 10. Then exit the loop !!

 

Case 6: Develop the URL detection script

The content is as follows:

#! /Bin/bash./etc/init. d/functionsfunction URL_Check () {wget -- spider http: // $1 &>/dev/null if ["$? "-Eq 0]; then action" $1 Detection successful! "/Bin/true else action" $1 Detection failed! "/Bin/false fi} web =" users "for url in $ web do URL_Check $ urldone

The running result is as follows:

The above is for reference only. If it is not well written, please forgive me, not professional

The analysis is as follows:

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.