Get the App
SLTechnology News&Howtos  ›  Servers  › 

Shell script-while Loop statement

Shulou Source: shulou.com Published: 2022-06-02 17:19:23 11月15日 Update

The difference between while and for:

For statements are ideal for situations where list objects are irregular and the source of the list is fixed.

While requires controlling the number of cycles, numbering the operands in numerical order, and performing repeated operations according to specific conditions.

When a condition is repeatedly tested, it will be executed repeatedly (infinitely) as long as the condition is established, unless forced termination, or the exit statement exits the script

Format: while conditional test operation (judgment statement) do command sequence done application field 1. Add user #! / bin/bashU= "student" / / name iTun1 / / default from the beginning while [$I-le 10] / / cycle ten times do useradd $Ubuni echo 123 | passwd-- stdin $Ubuni & > / dev/null set the password to 123 and output the result to the black hole iTunes + / / Second increment doneuntil [$I-gt 10] do useradd $Ubuni echo 123 | passwd-- stdin $Ubuni & > / dev/null let i++done

Create a while01.sh under the / opt directory

Write a script

When you are finished, save and exit add execution permissions to the file and start the following figure

The first run will not be displayed. This is the second run. If you report an error in the first run, you can check cat / etc/passwd.

two。 Interactive batch creation of users:

#! / bin/bashread-p "Please enter the prefix for creating users:" Xread-p "Please enter the number of users to be created:" Mread-p "Please enter the initial password for users:" Ni=1while [$I-le $M] / / the number of users to be created do useradd $le echo "$N" | passwd-- stdin $Xampi & > / dev/null / / password chage-d 0$ Xonomi / / No. Forced password change at one login, let i++done.

Then create a wheil02.sh and enter the content.

Add execution permission to run after saving and exiting

Check in cat / etc/passwd to see if the creation is complete.

To force a password change, you can try it in the virtual machine as shown below.

In this way, the amendment will be forced.

3. Guess the price game

#! / bin/bashP=$ (($RANDOM00)) T=0echo "the actual price range of the commodity is 09999, please guess what it is?" While truedo read-p "Please enter the number of prices you guessed:" INT let prices + if [$INT-eq $P]; then echo "Congratulations. The actual price is $P" echo "you guessed a total of $T times" exit 0 elif [$INT-gt $P] Then echo is too high, else echo is too low, fidone

Tags: User password input price condition force run statement script loop number actual object permission test guess right interactive content prefix Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Xiaomi MariaDB MySQL Microsoft