Linux Beginner's array and if statement for loop

Source: Internet
Author: User
Tags stdin egrep

Array


Variable: memory storage space;

Variable characteristics: Only one data can be stored in each variable, the variable can only be assigned once


An array of contiguous memory spaces that hold one or more elements, or a collection of multiple variables

Array elements: Any storage unit in the array that holds the data

Index of the array:

1. Numeric index: Indexed array (index arrays)

0,1,2,,,,,,

2. Name (meaningful string): Associative array (related array) (less)



Dense arrays and sparse arrays:

Dense arrays: Index numbers must be contiguous

Sparse arrays: Index numbers can be discontinuous, and bash arrays belong to this class


Define (DECLARE) an array:

1.declare command

Declare-i Name: Declares the name as an integer variable

-X: Declare name as environment variable


DECLARE-A Name: Declare name as an indexed array (if supported)

DECLARE-A Name: Declare name as associative array (if supported)


Declare-a name= ("VALU1" "VALLU2" "VALU3" ...)

Declare-a namee= ([0]= "value1" [1]= "value2" [5]= "Value3")


2. Declare the array directly:

Assign a value directly to an array:

Array_name= ("VALU1" "VALLU2" "VALU3" ...): Declare a dense array

Array_name= ([0]= "value1" [1]= "value2" [5]= "Value3") declares a sparse array


3. Create an array that defines the elements of the array:

Array_name=[0]=value1

Array_name=[1]=value2


To reference an element in an array:

Methods for referencing variables: ${name}

Methods for referencing array elements: ${array_name[index]}

Note that if you do not give an index number, the first element that references the array is the index=0 element


Referencing all elements of an entire array: ${array_name[*]} or ${array_name[@]}

Index of reference array: ${! Array_name[*]} or ${! Array_name[@]}


View the length of the array (number of valid elements in the array)

${#ARRAY_NAME [*]} or ${#ARRAY_NAME [@]}


Array slices:

${array_name:offset}: Displays the index position that includes the offset number and all elements of the subsequent German

${array_name:offset:number}: Displays the index position, including offset numbers, and the number of elements that are later


Append an element to an array

1. Dense array:

array_name[{$ #ARRAY_NAME [*]}]=valuen

2. Sparse Arrays:

Array_name[index]=valuen

Note: Index must be a number of array element indices that are not used


Undo Array:

Unset Array_Name

To delete an element in an array:

Unset Array_name[index]



Random variable 0-32767

Entropy Pool

/dev/random

/dev/urandom



Bash Script Programming:

Shell script Programming Features:

Over-programming languages

Scripting class Language

Interpreted language


Programming Languages:

Sequential execution Structure:

Executes all statements (commands) from left to right, top to bottom

The main structure of shell scripts;


Select the execution structure:

According to the logical judgment result of the given condition or according to the optional range of values, then select the statement in a branch to execute;

If: Branch selection criteria: The result of logical judgment;

Case: Branch selection criteria: Based on optional values;


Loop execution Structure:

For a particular statement, repeat 0 times, 1 or more times;

For: Iterates through the specified list;

While: according to the result of logical judgment;

Until: According to the result of logical judgment;

Select: The dead loop, using the loop mechanism to provide a choice list;


Select the execution structure:

If statement:

if command; then command; [elif command; then command;] ... [Else command;] Fi


If statement single branch structure: If the condition is true, then the command after then is executed, otherwise, no action is taken;

If CONDITION

Then STATEMENT

Fi


if CONDITION; Then

STATEMENT1

STATEMENT2

...

Fi


Note: You want to perform the statements after then, provided the condition part is true;


Double branching structure of the IF statement: Executes the command after then if the condition is true, or executes the command following the else;

if CONDITION; Then

STATEMENT

...

Else

STATEMENT

...

Fi


Multi-branch structure of the IF statement: first to determine if CONDITION1 is true, and if true, to execute the statement after the first then, or to determine if CONDITION2 is true, and if true, executes the statement after the second then Otherwise, the CONDITION3 is judged to be true, and if true, executes the statement after the third then ... If all condition are false, execute the statement after the else;

if CONDITION1; Then

STATEMENT

...

Elif CONDITION2; Then

STATEMENT

...

Elif CONDITION3; Then

STATEMENT

...

...

Else

STATEMENT

...

Fi


Recommendation: If multi-branch structure, can not be used;


User interaction for Bash scripting:

Positional parameter variables: $, $, $, ...

Special variables:

$#: The total number of all positional parameters;

$*: A list of all positional parameters given; When using double quotation marks, the entire argument list is treated as a string;

[Email protected]: A list of all positional parameters given; when there are double quotes, each parameter exists as a separate string;

$: The path of the script file itself executed;


Eg: Write a script to pass the user name parameter to the script, determine whether the number of parameters is qualified, and determine whether the user exists, if present, display the corresponding information, otherwise create and set a password for it;

#!/bin/bash

#

If [$#-ne 1]; Then

echo "Only one USERNAME can specified."

Exit 5

Fi


If ID $ &>/dev/null; Then

echo "$ exists already."

Else

Useradd $

echo $ | passwd--stdin $ &>/dev/null

echo "Create $ successfully."

Fi


Read command:

Read [-a array] [-P prompt] [-t timeout] [name ...]

The name is typically a variable or array name: If the name is not written, the system will save read read information in the reply variable;


Note: When using the Read command, the time-out is usually specified with the-t option, and once the time-out is defined with the-t option, we must later determine if the given variable is empty, and if NULL is required to provide a default value for the variable;


Eg: ability to add or delete user accounts, you can use the-a option to complete the addition, using the-d option to delete users;

#!/bin/bash

#

If [$#-ne 2]; Then

echo "Usage: $ (basename $)-a Username | -D Username. "

Exit 5

Fi


if [= = '-a ']; Then

If ID $ &>/dev/null; Then

echo "$ exists already."

Else

Useradd

echo | passwd--stdin &>/dev/null

echo "Create $ successfully."

Fi

Fi


if [= = '-d ']; Then

If ID $ &>/dev/null; Then

Userdel-r

echo "Delte finished."

Else

echo "User $ does not exist."

Fi

Fi


Eg:. Determine whether the given file size is greater than 100KB, if it is greater than 100KB, it is a large file, otherwise it will show that it is a small file;

#!/bin/bash

#

filesize=$ (Wc-c < $)

If [$FILESIZE-le 102400]; Then

echo "Big file."

Else

echo "Small file."

Fi


Eg: determines whether a given string is an integer

#!/bin/bash

#

If echo $ | grep "^\<[[:d igit:]]\+\>$" &>/dev/null; Then

echo "is integer."

Else

echo "is not an integer."

Fi



Positional parameter variables:

$, $, $, ...


Shift [N]

Shift position parameters.



Eg: ability to add or delete user accounts, you can use the-a option to complete the addition, using the-d option to delete users;

#!/bin/bash

# Author:zhao

# version:0.0.2

# Determine paraments Count

#

If [$#-ne 2]; Then

echo "Usage: $ (basename $)-a Username | -D Username. "

Exit 5

Fi


if [= = '-a ']; Then

Shift

If ID $ &>/dev/null; Then

echo "$ exists already."

Else

Useradd $

echo $ | passwd--stdin $ &>/dev/null

echo "Create $ successfully."

Fi

Fi


if [= = '-d ']; Then

Shift

If ID $ &>/dev/null; Then

Userdel-r $

echo "Delte $ finished."

Else

echo "User $ does not exist."

Fi

Fi




If statement multi-branch structure:

if CONDITION1; Then

STATEMENT

...

Elif CONDITION2; Then

STATEMENT

...

Elif CONDITION3; Then

STATEMENT

...

...

Else

STATEMENT

...

Fi


eg

A user is randomly selected from the same UID and GID in/etc/passwd to determine the user's type: UID is 0--> superuser, UID is between 1-999 and system user; 1000+ login user;

#!/bin/bash

#

lines=$ (egrep "\< ([[:d igit:]]+) \>.*\1"/etc/passwd | wc-l)

SEQUENCE=$[${RANDOM}%${LINES}+1]

username=$ (egrep "\< ([[:d igit:]]+) \>.*\1"/etc/passwd | head-n ${sequence} | tail-1 | cut-d:-F1)

userid=$ (egrep "\< ([[:d igit:]]+) \>.*\1"/etc/passwd | head-n ${sequence} | tail-1 | cut-d:-F3)


If [$USERID-eq 0]; Then

echo "$USERNAME is Super user."

elif [$USERID-ge 1000]; Then

echo "$USERNAME is Login User."

Else

echo "$USERNAME is System User."

Fi


Loop execution Structure:

Repeat the execution of a code 0 times, 1 times, or multiple times;

A good loop structure must include two of the most important links:

Conditions to enter the loop:

Conditions that are satisfied when the cycle begins;

Conditions to exit the loop:

The condition that the end of the cycle satisfies;


Bash script:

For

While

Until

Select


For loop:

1. Traversing the list

For Var_name in LIST; Do loop body; Done


For Var_name in LIST; Do

Loop body

Done


Var_name: Any specified variable name, the value of the variable is taken from the list and assigned value;

Loop body: Generally a combination of commands or commands that can be used with var_name; if the loop body does not include var_name, a dead loop may occur;

How the list is generated:

1) Give a direct

2) List of pure integers

SEQ: Output An integer list

seq [First [INCREMENT]] Last

3) curly braces unfold

{first.. Last}

4) return value of the execution result of the command

5) GLOBBING

6) references to certain variables: [email protected], $*


eg

Ability to add or remove user accounts, you can add one or more users using the-a option, and use the-d option to delete one or more users;

Example:

#!/bin/bash

#

If [$#-lt 2]; Then

echo "Usage: $ (basename $)-a User1 User2 ... | -D User1 User2 ... "

Exit 5

Fi


if [= = '-a ']; Then

Shift

For I in $*; Do

If ID $I &>/dev/null; Then

echo "$I exists already."

Else

Useradd $I

echo $I | passwd--stdin $I &>/dev/null

echo "Create $I successfully."

Fi

Done

Fi


if [= = '-d ']; Then

Shift

For J in $*; Do

If ID $J &>/dev/null; Then

Userdel-r $J

echo "Delte $J finished."

Else

echo "User $J does not exist."

Fi

Done

Fi


For loop:

Enter the condition of the loop: the list has elements that can be accessed;

Exit loop Condition: List in order to be emptied, no elements available;


Features of the For loop:

1. There is almost no cycle of death;

2. During the execution of the loop, the list needs to be loaded into memory, so it may consume too much memory and CPU resources for large lists;


Eg: calculates the and of all integers within 100;


#!/bin/bash

#

Read-t 5-p "Please input a integer[0]:" Integer


If [-Z $INTEGER]; Then

Integer=0

Fi


if! echo $INTEGER | Grep-q "^\<[[:d igit:]]\+\>$"; Then

echo "You must input an integer."

Exit 5

Fi


For I in $ (seq $INTEGER); Do

# Let sum+= $I

# let sum= $SUM + $I

Sum=$[sum+i]

Done

Echo $SUM




Eg: write a script that prints an inverted isosceles triangle composed of *;

#!/bin/bash

#

Linenum=$1

For I in $ (seq $LINENUM); Do

For J in $ (seq $[i-1]); Do

Echo-n ""

Done

For K in $ (seq $[2* (linenum-i) +1]); Do

Echo-n "*"

Done

Echo

Done


Eg: print 99 multiplication table

#!/bin/bash

#

For I in {1..9}; Do

For J in $ (seq $I); Do

Echo-ne "$I * $J =$[i*j]\t"

Done

Echo

Done


1x1=1 1x2=2 1x3=3 ... 1x9=9

2x2=4 2x3=6 ... 2x9=18

...

9x9=81


Note: When using a For loop nesting, the outer for loop controls the output of the number of rows, and the inner for Loop, which controls the output of the number of columns;


2. Control variables

for (expression 1; expression 2; expression 3); Do command; Done


for (expression 1; expression 2; expression 3); Do

Loop body

Done


Expression 1: Assigns the initial value to the variable;

Expression 2: The exit condition of the loop;

Expression 3: Variable value of the law of Change;



Linux Beginner's array and if statement for loop

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.