Shell Learning for Loop statement "Beginner"

Source: Internet
Author: User
Tags echo command stdin



Preface: There are a lot of instructions in daily system management that need to be run repeatedly,Shell programming provides for,while,until ,Select Loop statement to implement the function of the repeated execution of a specific instruction, in all the loop statements, the variable must have the initial value, each time the command sequence is run before the condition should be filtered to meet the criteria to run the command, Otherwise, no action is taken. The following is a description of the two syntax formats for a FOR loop statement.



for Loops each time the information in the list is processed until the loop is exhausted. a loop that is relative to while and until is a condition that must be met for a given syntax, which is a state that has been known to perform several loops.





Syntax Format 1 :



For variable in value 1 value 2 value 3 ....



Do



Execute the program



Done


Description:ForThe statement determines the number of times the loop executes, depending on the number of times the variable is assigned, by the value defined by the forThe instructions within the loop will be executed the same number of times, such as defining a variableIvalue is2,3,4, the final forthe loop executes the command three times. forsyntax format for statements1assigning values to variables isinchdirectly after the assignment, multiple assignments are separated by a space. When the value of the variable is in the list, forThe loop executes once so the command uses the variable name to get the current value in the list. command can be used for any validShellcommands and statements.


inch The list can contain replacements, strings, and file names



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





simple for Loop example



Example 1: outputting numbers in a list sequentially:

[[email protected] sh] # vi for1.sh
[[email protected] sh] # cat for1.sh
#! / bin / bash
for i in 1 2 3 4 5 ## i is a variable, 1 2 3 4 5 is assigned to the variable i
do
echo $ i
done
[[email protected] sh] # ./for1.sh ## Execution result

You can also use variable names and strings in combination with loop weight, as follows.

echo "The value is: $ i"
Output result:
The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5


Example 2: Print a list of strings

In the following for loop, the list contains the string "orange red blue grey", the command is echo, and the variable name is loop,

The echo command uses $ loop to feed back all the values in the list until the list is empty.

[[email protected] sh] # vi forloop.sh
[[email protected] sh] # cat forloop.sh
#! / bin / bash
for loop in orange red blue grey
do
echo $ loop
done
[[email protected] sh] # ./forloop.sh ## Execution result
orange red blue grey
 ## Combining variable names with strings in loop weight


Example 3: Simple batch decompression script (here the script is replaced with the batch query file number)

[[email protected] sh] # vi for2.sh
[[email protected] sh] # cat for2.sh
#! / bin / bash
cd / mnt / sh / ## First enter the corresponding directory
ls * .sh> ls.log ## In the sh directory, list all files ending in .sh, and overwrite them in the ls.log file (overwrite is used here instead of appending because it is not sure about ls.log Whether the file actually exists, if it will affect the program execution, so use overwrite)
y = 1 ## Set variable y = 1
for i in $ (cat ls.log) ## Assign the variable i to the output of cat ls.log
do
echo $ y ## output variable y value, output a result and assign y to 1
y = $ (($ y + 1)) ## Variable y = variable y + 1 (double parentheses are required to add, subtract, multiply, and divide)
done
[[email protected] sh] # ./for2.sh ## Execution result

[[email protected] sh] # ls ## Check the execution result to see how many files ending in .sh
for1.sh for2.sh for3.sh for4.sh if1.sh if2.sh if3.sh if4.sh ls.log
[[email protected] sh] #
Can be modified to print all files in the current directory

[[email protected] sh] # cat for5.sh
#! / bin / bash
for i in `ls`
do
echo $ i
done
[[email protected] sh] # ./for5.sh
for1.sh
for2.sh
for3.sh
for4.sh
for5.sh
if1.sh
if2.sh
if3.sh
if4.sh
ls.log


Syntax format 2:

for ((initial value; cycle control condition; variable change))

do

execute program

done

Note: Syntax format 2 is to first initialize the value of the variable, that is, define the initial value of a variable, and then modify the value of the variable through operation. When the condition for ending the loop is met, the for loop ends.

Initial value: The initial value of a variable before the loop is set directly in a manner similar to i = 1.

Cyclic control conditions: When the variable value is within the scope of the cyclic control, execution can continue. For example i <= 100

Variable change: The change of the variable every time a cycle is made. For example: i = i + 1

It is worth noting that in the setting of "variable change", if you add 1 every time, you can use a method similar to "i ++", that is, i will increase by 1 every cycle. You can do a loop from 1 to 100 in this way

 

Example 1: Loop from 1 to 100

[[email protected] sh] # vi for3.sh
[[email protected] sh] # cat for3.sh
#! / bin / bash
x = 0
for ((x = 1; x <= 100; x = x + 1)) ## First initial value x = 1 semicolon When the execution loop control condition judges x <= 100, when the execution variable changes x = x + 1
do
y = $ (($ y + $ x)) ## Variable y is equal to variable y + variable x
done
echo "The sum of 1 + 2 + ... + 100 is: $ y" ## When the value of x is less than or equal to 100, the output of the variable y is equal to the variable y plus the variable x
[[email protected] sh] # ./for3.sh
The sum of 1 + 2 + ... + 100 is: 5050 ## Execution result
[[email protected] sh] #


Example 2: Add a specified number of users in batches (if condition judgment is used in combination with a for loop)

[[email protected] sh] # vi for4.sh
[[email protected] sh] # cat for4.sh
#! / bin / bash
read -t 30 -p "input name:" name
read -t 30 -p "input num:" num
read -t 30 -p "input password:" password
 
if [! -z $ name -a! -z $ num -a! -z $ password]
then
y = $ (echo $ num | sed ‘s / ^ [0-9] * $ // g‘)
if [-z "$ y"]
then
for ((i = 1; i <= $ num; i = i + 1))
do
useradd "$ name $ i" &> / dev / null
echo $ password | passwd --stdin "$ name $ i" &> / dev / null
done
fi
fi
[[email protected] sh] # ./for4.sh
input name: zhangsan
input num: 5
input password: abc123
[[email protected] sh] # ls / home ## Go to the home directory to view the execution result, there is Zhang San user instructions to add ok
lost + found zhangsan1 zhangsan2 zhangsan3 zhangsan4 zhangsan5
[[email protected] sh] #
read -t 30 specifies a read time of thirty seconds

read -p "input name:" Set input name: the prompt when reading the value

! Negate

-z returns true if this value is empty. Plus! Representation: The following statement can be executed only if there is a value.

-a logical AND (simultaneous judgment)

echo $ num | sed 's / ^ [0-9] * $ // g': After filtering the output variable num result pipe character, use regular sed to determine whether the output is a number, if it is, it will replace the variable result with empty . (In actual life, if you add users yourself in batches, it is not that cumbersome, and you still have to judge whether the number of input users is numeric, this if statement can be omitted completely)

-z "$ y": variable y is empty, return true

i = 1; i <= $ num; i = i + 1 refer to i = 1; i <= 100; i = i + 1 explanation

useradd "$ name $ i" &> / dev / null: create a user-defined variable name + number, and import the execution result into a black hole

echo $ password | passwd --stdin "$ name $ i" &> / dev / null: input the password pipeline to the user with custom variable name + number, and the execution result is imported into the black hole

 

Attachment: a brief introduction to the read command

The read command reads the value of a variable from the keyboard, and is usually used in shell scripts to interact with users. This command can read the values of multiple variables at once, and the variables and the entered values need to be separated by spaces.

Syntax: read (option) (parameter)

Options:

-p: specify the prompt when reading the value

-t: Specify the waiting time (seconds) when reading the value

Parameter: Specify the variable name to read



This article is from the "NJ Xiaosheng" blog, please be sure to keep this source http://qingwl.blog.51cto.com/9853378/1919786

shell learning for loop statement [beginner]

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.