Function of script programming:
Function: Functions
Structured programming, cannot run independently, needs to be executed when called, can be invoked multiple times
Define a function:
function FUNCNAME {
Command
}
FUNCNAME () {
Command
}
Custom execution Status return value:
Return #
0-255
Functions that Accept parameters:
./a.sh m N
$1:m
$2:n
Twoint 5 6
$1:5
$2:6
Exercise: Write a script that determines which hosts are online between 192.168.0.200-192.168.0.254. Requirements:
1, the use of functions to achieve a host of the decision process;
2. Call this function in the main program to determine the online status of all hosts within the specified range.
#!/bin/bash
#
PING () {
For I in {200..254};d o
If Ping-c 1-w 1 192.168.0. $I &>/dev/null; Then
echo "192.168.0. $I is up."
Else
echo "192.168.0. $I is down."
Fi
Done
}
Ping
#!/bin/bash
#
PING () {
If Ping-c 1-w 1 $ &>/dev/null; Then
echo "is up."
Else
echo "is down."
Fi
}
For I in {200..254}; Do
PING 192.168.0. $I
Done
#!/bin/bash
#
PING () {
If Ping-c 1-w 1 $ &>/dev/null; Then
return 0
Else
Return 1
Fi
}
For I in {200..254}; Do
PING 192.168.0. $I
If [$?-eq 0]; Then
echo "192.168.0. $I is up."
Else
echo "192.168.0. $I is down."
Fi
Done
Write a script: Use the function to complete
1, the function can accept a parameter, the parameter is the user name;
Determine if a user exists
Returns the shell and UID of this user if it exists, and returns the normal status value;
If it does not exist, it says that the user does not exist and returns an error status value;
2, the function is called in the main program;
Extension 1: In the main program, let the user enter the user name, passed to the function to judge;
Extension 2: In the main program, after entering the user name judgment does not exit the script, but prompts the user to continue to enter the next user name, if the user entered the user does not exist, please re-enter the user, but if the user entered Q or Q to exit;
#!/bin/bash
#
User () {
If ID $ &>/dev/null; then
echo "' grep ^$1/etc/passwd | cut-d:-f3,7 ' "
return 0
Else
echo "No"
Return 1
Fi
}
Read-p "Please input username:" Username
until [$username = = Q-o $username = = Q]; Do
User $username
If [$? = = 0];then
Read-p "Please input again:" username
Else
Read-p "No $username, please input again:" username
Fi
Done
Shell Programming Basics-function: Features