Shell script Application (iii) for, while, case statements

Source: Internet
Author: User
Tags case statement control characters stdin

Foreword: It is difficult to write all the code in sequential order when it is hard to satisfy the requirements when facing various lists and repeating tasks. Use other program control structures such as loops, branches, and more to make it easier to perform more complex and powerful functions.
1. Using the FOR Loop statement
For statement structure:
For variable name in value list
Do
Command sequence
Done
Structure of the FOR Loop statement:

1) Bulk Add users by Name list
Prepare the Employee list file Users.txt, and then write a script called uaddfor.sh, which reads each user name from the Users.txt file, repeats the add user, and sets the initial password for the associated action.
[[email protected] ~]# vim/root/user.txt//list file used as a test
Chenpeng
Dengchao
Zhangjie
To add a user's script in bulk
[Email protected] ~]# vim uaddfor.sh
#!/bin/bash
ulist=$ (Cat/root/user.txt)
For uname in $ulist
Do
Useradd $uname
echo "123456" | passwd--stdin $uname &>/dev/null
Done
[[email protected] ~]# chmod +x uaddfor.sh//Add Execute permission
[[email protected] ~]#./uaddfor.sh//test and confirm execution results
[Email protected] ~]# tail-3/etc/passwd
Chenpeng:x:501:501::/home/chenpeng:/bin/bash
Dengchao:x:502:502::/home/dengchao:/bin/bash
Zhangjie:x:503:503::/home/zhangjie:/bin/bash
2) To delete the user added by the uaddfor.sh script, simply delete the user's command from the script above.
[email protected] ~]# CP uaddfor.sh udelfor.sh
[[email protected] ~]# vim udelfor.sh//Bulk Delete user's script
#!/bin/bash
ulist=$ (Cat/root/user.txt)
For uname in $ulist
Do
Userdel $uname
echo "123456" | passwd--stdin $uname &>/dev/null
Done
[Email protected] ~]# chmod +x udelfor.sh
[Email protected] ~]#./udelfor.sh
[[email protected] ~]# ID Chenpeng
Id:chenpeng: No such user
After executing the script, the user has been removed
3) View host status based on IP address list
First establish the IP address list file Ipadds.txt, then write a shell script named chkhosts.sh, read the IP address of each server from the Ipadds.txt file, repeat ping connectivity test, and output the corresponding prompt according to the test results.
[[email protected] ~]# vim/root/ipadds.txt//list file used as a test
192.168.1.1
192.168.1.2
192.168.1.10
[[email protected] ~]# vim/chkhosts.sh//loop check each host's script
#!/bin/bash
hlist=$ (Cat/root/ipadds.txt)
For IP in $hlist
Do
Ping-c 3-i 0.2-w 3 $ip &>/dev/null
If [$?-eq 0]
Then
echo "Host $ip is Up"
Else
echo "Host $ip is down"
Fi
Done
Execute script
[Email protected]/]# chmod +x chkhosts.sh
[Email protected]/]#./chkhosts.sh
Host 192.168.1.1 is up
Host 192.168.1.2 is down
Host 192.168.1.10 is down
2. Using the While Loop statement
The For loop is irregular, the list is fixed, while the loop is appropriate for the number of cycles required, the operand is numbered numerically, and repeated operations are performed on a specific condition.
The syntax structure of the while statement:
While condition test action
Do
Command sequence
Done
The structure of the while loop statement:

1) batch Add the regular number of users, add 20 users, the name is STU1,STU2, ... Stu20
[Email protected]/]# vim uaddwhile.sh
#!/bin/bash
prefix= "Stu"
I=1
While [$i-le 20]
Do
Useradd ${prefix} $i
echo "123456" | passwd--stdin ${prefix} $i &>/dev/null
Let i++
Done
[Email protected]/]# chmod +x uaddwhile.sh
[Email protected]/]#./uaddwhile.sh
[[email protected]/]# grep "Stu"/etc/passwd | Tail-3
Stu18:x:518:518::/home/stu18:/bin/bash
Stu19:x:519:519::/home/stu19:/bin/bash
Stu20:x:520:520::/home/stu20:/bin/bash
2) Delete the added user, just change the above code Useradd to Userdel
[email protected]/]# CP uaddwhile.sh udelwhile.sh
[Email protected]/]# vim udelwhile.sh
#!/bin/bash
prefix= "Stu"
I=1
While [$i-le 20]
Do
Userdel ${prefix} $i
echo "123456" | passwd--stdin ${prefix} $i &>/dev/null
Let i++
Done
[Email protected]/]# chmod +x udelwhile.sh
[Email protected]/]#./udelwhile.sh
[[email protected]/]# ID stu20
Id:stu20: No such user
3) Guess the price of the game
The case requirements are as follows: The script pre-generates a random price number (0~999) as the actual price, to determine whether the user guessed the price is higher or lower than the actual price, give the corresponding prompt enough to ask the user to guess again, until the user guessed the actual price, the output of the number of user guesses, the actual price.
Idea: Through the environment variable random can get a random integer less than 2 16, calculate its remainder with 1000 to obtain a random price of 0-999, the repeated guessing operation can be achieved by true as the test condition of the while loop implementation, when the user guessed the actual price of the end loop, The process of judging the guessing price and the actual price is implemented by the IF statement, nested in the while loop body, using variables to record the number of guesses.
[Email protected]/]# vim pricegame.sh
#!/bin/bash
price=$ (expr $RANDOM% 1000)
Times=0
echo "Shangpin 0-999,ni cai?"
While True
Do
Read-p "Qing shu ru:" INT
Let times++
If [$INT-eq $price]; Then
echo "Gongxi, Jiageshi: $price"
echo "Ni cai le $TIMES ci"
Exit 0
elif [$INT-gt $price]; Then
echo "Taigaole"
Else
echo "Taidile"
Fi
Done
[Email protected]/]# chmod +x pricegame.sh
[Email protected]/]#./pricegame.sh
Shangpin 0-999,ni Cai?
Qing Shu ru:500
Taigaole
Qing Shu ru:400
Taidile
Qing Shu ru:450
Taidile
Qing Shu ru:470
Taigaole
Qing Shu ru:469
Taigaole
Qing Shu ru:460
Gongxi, jiageshi:460
Ni cai le 6 ci
3. Using CASE Branch statements
Case statements can be more clearly structured using a scripting program. Very similar to the IF statement, except that the IF statement needs to judge many different conditions, whereas the case statement simply determines the different values of a variable.
Syntax structure of the case Branch statement:
Case Variable value in
Mode 1)
Command sequence 1
;;
Mode 2)
Command Sequence 2
;;
......................
)
Default command sequence
Esac
(
is a wildcard character that can match any value)
The structure of the case Branch statement:

When you use the case branching statement, you need to be aware that:
1,case the end of the line must be the word "in", each pattern must be closed with a closing parenthesis ")"
2, double semicolon ";;" indicates the end of the command sequence
3, in the pattern string, you can use square brackets to denote a contiguous range, such as "0-9", or you can use the vertical bar symbol "|" Express or, for example, "a| B
4, the Last " ) "represents the default mode, where theEquivalent to a wildcard character
1) Check the user input a character, through the case statement to determine whether the character is a letter, an array or other control characters, and give the corresponding prompt information.
[Email protected]/]# vim hitkey.sh
#!/bin/bash
Read-p "Qingshuru:" KEY
Case ' $KEY ' in
[A-z] | [A-z])
echo "ni shu ru de shi Zimu"
;;
[0-9])
echo "ni shu ru de shi Shuzi"
;;
)
echo "ni shu ru de shi Qita"
Esac
[Email protected]/]# chmod +x hitkey.sh
[Email protected]/]#./hitkey.sh
Qingshuru:z
Ni shu ru de shi Zimu
[Email protected]/]#./hitkey.sh
Qingshuru:7
Ni shu ru de shi Shuzi
[Email protected]/]#./hitkey.sh
Qingshuru:/
Ni shu ru de shi Qita
2) writing system service scripts
The Start,stop,restart,status control parameters specified by the location variable are used to start, stop, restart the sleep process, and to view the status of the sleep process, respectively.
[Email protected]/]# vim Myprog
#!/bin/bash
#chkconfig-90 10
#description: AAAAAAAAAA
Case "$" in
Start
Echo-n "Zhengzaiqidong sleep Fuwu ..."
If sleep 7200 &//Start sleep process in the background
Then
echo "OK"
Fi
;;
Stop
Echo-n "Zhengzaitingzhi Sleep Fuwu"
Pkill "Sleep" &>/dev/null//Kill sleep Process
echo "OK"
;;
Status
If Pgrep "Sleep" &>/dev/null; then//Judge and prompt the sleep process state
echo "Sleep Fuwu Yiqidong"
Else
echo "Sleep Fuwu Yitingzhi"
Fi
;;
Restart)//stop first, then start the service
$ stop
$ start
;;
)//Display usage information by default
echo "YONGFA: $ {Start|stop|status|restart}"
Esac
[Email protected]/]# chmod +x Myprog
[[email protected]/]#./myprog start
Zhengzaiqidong Sleep Fuwu...ok
[Email protected]/]#./myprog status
Sleep Fuwu Yiqidong
[[email protected]/]#./myprog stop
Zhengzaitingzhi Sleep Fuwuok
[[email protected]/]#./myprog Reload//This parameter is not provided and is processed by default
YONGFA:./myprog {Start|stop|status|restart}

Then execute the following command to add Myprog to the system service
[email protected]/]# CP myprog/etc/init.d/

Shell script Application (iii) for, while, case statements

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.