Get the App
SLTechnology News&Howtos  ›  Servers  › 

Case statement and Loop statement in shell programming

Shulou Source: shulou.com Published: 2022-06-03 07:28:53 09月21日 Update

Case multi-branch statement

Case statement structure: execute different command sequences according to different values of variables

Case variable value in mode 1) command sequence 1; mode 2) command sequence 2;; *) default command sequence esac

";" indicates the end of a sentence.

The "if,else" statement applies to an interval range

"the case' statement is suitable for matching a fixed value

An example of the application of case statement:

1. Determine whether the input character is a number, letter, or symbol

two。 Judge whether the input performance is good or bad

Loop statement

The structure of the for statement: read different variable values to execute the same set of commands one by one

For variable name in value list do command sequence done

Take a value from the list of values from top to bottom to assign a value to the variable, and then output

An example of the Application of for sentence

1. Add users in batch

The user name is stored in the users.txt file, one per line

The initial passwords are all set to 123456

Validate script

two。 Use the ping command to view connectivity to each host

Save the results to shuju.txt

The structure of the while statement: repeatedly test a condition and execute it repeatedly as long as the condition is established

While conditional Test Action do Command sequence done

An example of the application of while statement:

1. Add users in batch

The user name begins with stu and is numbered in numerical order

Add a total of 20 users, namely stu1, stu2, … 、 stu20

The initial passwords are all set to 123456

The structure of the until statement: test a condition repeatedly, and execute it repeatedly as long as the condition is not valid

Until conditional Test Action do Command sequence done

An application example of until sentence

1. The sum of 1-50 is calculated by cyclic accumulation.

Tags: Statements commands sequences conditions users instances structures tests differences variables loops passwords numbers patterns values input one sentence host branch interval Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple macOS Microsoft Huawei Redmi