1、for Loop Introduction
for A cycle is a fixed cycle , In other words, you know how many times you need to do the loop , Sometimes I put for A loop is called a counting loop .
stay Shell in for There are two kinds of syntax for loops :
# grammar 1:
for Variable in value 1 value 2 value 3 …
do
Program
done
In this grammar for Number of cycles , Depending on in The number of the following values ( The blank space to separate ), If there are a few values, loop them a few times , And each loop assigns the value to the variable . in other words , hypothesis in Then there are three values ,for It's going to cycle three times , The first loop will put the value 1 Assign variable , The second loop will put the value 2 Assign variable , And so on .
# grammar 2:
for(( Initial value ; Cycle control conditions ; Variable change ))
do
Program
done
Attention should be paid to Grammar 2 :
- Initial value : At the beginning of the loop , You need to give a variable an initial value , Such as
i=1; - Cycle control conditions : Used to specify the number of times the variable loops , Such as
i<=100, Then as long as i Is less than or equal to 100, The cycle will continue ; - Variable change : After each cycle , How the variable should change , Such as
i=i+1, After each cycle , VariableiAll the values are added 1.
2、 Example
An example of grammar :
demand : Print time .
# Create script file
[[email protected] ~]# vim sh/for.sh
#!/bin/bash
for time in morning noon afternoon evening
do
echo "This time is $time!"
done
Executing the script results in :
[[email protected] tmp]# chmod 755 for1.sh
[[email protected] tmp]# ./for1.sh
This time is morning!
This time is noon!
This time is afternoon!
This time is evening!
Grammar 2 example :
Grammar two is the same as in other languages for The loop is similar , That is, the number of cycles is fixed in advance .
demand : from 1 Add to 100.
#!/bin/bash
# Define a summation variable sum
sum=0
# Define the cycle 100 Time
# stay Shell If you want to carry out mathematical operations , It needs to be enclosed in double parentheses , To recognize that there are numerical operations in brackets .
for((i=1;i<=100;i=i+1))
do
# Each loop gives a variable sum assignment
sum=$(($sum+$i))
done
# Output 1 Add to 100 And
echo "The sum of 1+2+...+100 is :$sum"
3、for Cycle summary
- The first format
forLoops are the most common Shell Circulation mode . - The second format
forLoops are suitable for mathematical operations , You can easily specify the number of cycles .
4、 practice : Batch decompress scripts
Mode one : Batch UnZip
# Create script file auto-tar.sh
[[email protected] ~]# vim sh/auto-tar.sh
# Batch decompress scripts
#!/bin/bash
# Enter the compressed package directory .
cd /tmp/sh/tar
# hold tar File names of all compressed packages in the directory , Save to tar.log In file .
# single > Is overlay .
# and tar.log Each file name is a line .
ls *.tar.gz>tar.log
# hold tar Directory .tgz The name of the compressed package of type is also appended to tar.log In file .
# double >> It's an addition .
ls *.tgz>>tar.log &>/dev/null
# Tips : In the way above , Put the names of all types of compressed files that need to be unzipped , All saved to tar.log In file .
# Read tar.log The content of the document , How many values are there in the file , How many times will it cycle ,
# Each loop assigns the file name to the variable i
for i in $(cat tar.log)
do
# decompression , And discard all output
tar -zxvf $i &>/dev/null
# Note that if there are other compressed packages , It needs to be done here if Judge ,
# Decompress the compressed files in different formats .
# The same goes for mode 2 .
done
# Delete temporary files tar.log, Because the script will not work after execution .
rm -rf /tmp/sh/tar/tar.log
explain :
In the first way for loop ,in There are several values after , Just cycle a few times , Values should be separated by spaces .
and tar.log What's in the file is 6 The file name of a compressed package , And each file name is on one line ,
[[email protected] tmp]# cat tar.log
apr-1.4.6.tar.gz
apr-util-1.4.1.tar.gz
httpd-2.4.7.tar.gz I
mysq1-5.5.23.tar.gz
php-5.6.15.tar.gz
phpMyAdmin-4.1.4-al1-languages.tar.gz
This format , It is equivalent to calculating one value per line , So you can cycle 6 Time , The value of each time is the file name of a compressed package ,
This completes the batch decompression of the required files .
Mode two : Batch UnZip
use for The second method of the loop is batch decompression , There are two things to note .
- First of all : You need to know the total number of compressed packets , Because I need to use
forThe second format of the loop is used for batch decompression , You need to know how many times to cycle .
Solution : Save all the file names of the files to be unzipped into a file ( The temporary file ), At this time, the file name of the file to be decompressed becomes a string , And then throughwcCommand to make statistics . - second : You need to extract the name of each compressed package , Assignment in variables .
Is the first cycle , The file name of the first package is assigned in the variable , The second cycle , Variable to assign the file name of the second package , Then you can usetarThe command unzips the compressed package .
#/bin/bash
# Enter the compressed package directory .
cd /tmp/sh/tar
# hold tar File names of all compressed packages in the directory , Save to tar.log In file .
# single > Is overlay .
# and tar.log Each file name is a line .
ls *.tar.gz>tar.log
# hold tar Directory .tgz The name of the compressed package of type is also appended to tar.log In file .
# double >> It's an addition .
ls *.tgz>>tar.log &>/dev/null
# Tips : In the way above , Put the names of all types of compressed files that need to be unzipped , All saved to tar.log In file .
# wc -l Command statistics line number , That is, get the number of files .
num=$(cat /tmp/sh/tar/tar.log | wc -l) # perhaps :wc -l /tmp/sh/tar/tar.log
# Start traversing the extracted file
for((i=1;i<="$num";i=i+1))
do
# use awk Command to extract the file name , To get the file name of the extracted file
# NR yes awk Built in variables for , At present awk Rows processed , Is the row number of the total data .
# Be careful '$i' This place , Still use single quotes , Using double quotation marks will report an error .
# awk 'NR=='$i' {print $1} It means to get the column information of the row .
filename=$(cat tar.log | awk 'NR=='$i' {print $1})
# Unzip the file
tar -zxvf $filename -C /tmp/sh/tar
done
# Delete temporary files tar.log
rm -rf /tmp/sh/tar/tar.log
summary :
forThe first way to cycle , For a Shell Script writing , It's simpler .
『 Forget to learn again 』Shell Process control — 36、for More related articles of circular Introduction
- 『 Forget to learn again 』Shell Basics — 8、 Introduction to pipeline symbols
We've already written about pipe symbols before , Today, let's briefly summarize the usage . 1. Line extraction command grep grep Role of command , Is in the specified file , Search for qualified strings . Command format : [[email protected] ~ ] ...
- 『 Forget to learn again 』Shell Basics — 1、Shell Introduction to
Catalog 1.Shell The origin of 2.Shell Two ways of executing instructions 3. What is? Shell Script 4.Shell Is a scripting language 1.Shell The origin of We are familiar with Windows Graphical interface of the system , For graphical interfaces ...
- 『 Forget to learn again 』Shell Basics — 10、Bash Special symbols in ( Two )
Tips : This article is followed by an article , Mainly about () Parentheses and {} The difference and use of braces . 8.() parentheses (): Used when a series of commands are executed ,() The command in will be in the sub Shell Run in .( Together with the braces below ) 9.{} Curly braces {}: ...
- 『 Forget to learn again 』Shell Basics — 3、echo Introduction and use of command
Catalog 1.echo Role of command 2.echo Basic usage of commands 3.echo Ordered -e Option usage 4.echo Some special uses of commands (1) The output character has a font color (2) The output character has a background color Talking about Shell Before the script , ...
- 『 Forget to learn again 』Shell Basics — 4、Bash Basic function (history command )
Catalog 1.history History commands 2. Set the number of command history records 3. Clear history command 4. Call of history command 5. Completion of commands and files stay Linux Default... In the system Shell Namely Bourne-AgainShell( abbreviation ...
- 『 Forget to learn again 』Shell Basics — 9、Bash Special symbols in ( One )
Catalog 1. Double single quotation mark 2. Double quotes 3.$ Symbol 4. The quotation marks 5.$() Symbol 6.# Symbol 7.\ Symbol 1. Double single quotation mark '': Single quotation marks . All special symbols in single quotation marks , Such as $ and "`"( The quotation marks ) Nothing special ...
- 『 Forget to learn again 』Shell Basics — 11、 Rules and classification of variable definition
Catalog 1. Rules for defining variables 2. Classification of variables 1. Rules for defining variables When you define variables , There are some rules to follow Variable names can be alphabetized . Numbers and underscores , But it can't start with a number . If the variable name is 2name It's wrong . stay Bash ...
- 『 Forget to learn again 』Shell Basics — 2、Shell Function and classification of
Catalog 1.Shell The role of 2.Shell The classification of 1.Shell The role of Shell In addition to being able to interpret user input commands , Pass it to the kernel , just so so : Call other programs , Passing data or parameters to other programs , And get the processing result of the program . stay ...
- 『 Forget to learn again 』Shell Basics — 5、Bash Basic function ( Command aliases and common shortcuts )
Catalog 1. Alias the command (1) Format the alias command (2) The command alias takes effect permanently (3) Alias priority 2.Bash Common shortcut key 1. Alias the command Linux The command alias of the system, as we have said before , Go over here . ...
- 『 Forget to learn again 』Shell Basics — 6、Bash Basic function ( I / O redirection )
Catalog 1.Bash Standard input and output of 2. Output redirection (1) Standard output redirection (2) Standard error output redirection (3) Correct output and error output are saved at the same time 3. Input redirection 1.Bash Standard input and output of We've been talking about , stay Li ...
Random recommendation
- eclipse Import the project Archive for required library cannot be read or is not a valid ZIP file
reason : Some of the files are damaged . terms of settlement :1. stay eclipse Run in maven clean install 2. Report errors , Find the file that reported the error and delete it physically , And then rerun maven clean install 3. Follow ...
- js The three ways of inheritance and their advantages and disadvantages
[ turn ] The first one is ,prototype The way : // Parent class function person(){ this.hair = 'black'; this.eye = 'black'; this.skin = ' ...
- Apache Configure multiple domain names AH00548: NameVirtualHost has no effect and will be removed in the next release
httpd-vhosts.conf The first line in the NameVirtualHost *:80 Delete it to solve the problem .
- About 6410 Of sd Card and nandflash The difference of startup
Today in the company, our captain asked me a question , About cortex Of sd Start the process and nandflash Startup process , I can't remember , I had nothing to do at noon 6410 The difference between the two startup modes of . Write here . If there is something wrong, please point out , I am right. ...
- DelphiXE Next String turn PAnsiChar( Reverse conversion )
A lot of information only mentions promotion to xe, And we call the bottom version c++ Developed programs , Yes, you can only press Ansi Operation of the , So you need to reverse the conversion . var s:PansiChar;s:=PansiChar(AnsiString(' I'm just ') ...
- js in substr And substring The difference between
Js Of substring and C# Of Substring The function of is to intercept a substring from a string , But their usage is very different , Let's compare them : Js Of substring grammar : Program code S ...
- c# The parameters of the event handler in the tutorial
Event handling functions generally have two parameters , The first parameter (object sender) Is the property of the object that generated the event Name Value , For example, click the button with the title in red , The first parameter sender The value of is button1. For example, press... If the title is red ...
- Do you really need to quit —— Besides, Android Program exit function
Do you really need to quit -- Besides, Android Program exit function To make Android It's been developing for a while , Believe a lot from Windows Developed Android Programmers are used to meeting the same problem as me : How to exit the process completely ...
- be based on TensorFlow Implement document detection on mobile terminal
author : Feng Xun Preface This article is not an introduction to neural networks or machine learning , But through a real product case , It shows the key technology points of running a neural network on the mobile client In the field of convolutional neural networks , There have been some classic image classification networks , Than ...
- linux introduction --Linux Desktop Environment ( Desktop system ) parade [ Additional advantages and disadvantages ]
In the early Linux All systems have no interfaces , It can only be managed by command , Like running a program . Edit document . Delete files, etc . therefore , If you want to use it skillfully Linux, You have to remember a lot of commands . Later, along with Windows The popularity of , The computer interface becomes more and more ...









