Shell script programming for statement, if statement use introduction _linux shell

Source: Internet
Author: User
Tags file size stop script

Upper:

Process oriented:
Sequential execution
Select execution: If, case
Loop execution: For, while, until

One, for statement

Format:
for variable in list;
Statement 1;
Statement 2;
...
Done
Example 1, write a script, add 10 users, and let each user's password with the user name "

Copy Code code as follows:

#!/bin/bash
For I in {1..10}; Todo
Useradd user$i;
echo user$i | passwd--stdin user$i
Done

Example 2, write a script that shows the timestamp of the/tmp/1.dir/tmp/2.dir/tmp/3.dir three files, and change the time of the three files to 201003030303.03

Copy Code code as follows:

#!/bin/bash
For Dir In/tmp/1.dir/tmp/2.dir/tmp/3.dir; Todo

Stat $Dir
Touch-m-T 201003030303.03 $Dir
Stat $Dir
Done

Types of arguments for bash:
Local variables
Local variables
Environment variables
Position variables: $, $, $, $ ....
Special variables:
$?: The state return value used to save the command just executed;
0: Successful execution; 1-255: Failure, 1,2,127
You can use the Exit command to customize the script execution state return value in a script, or, if not defined, the script execution status returned
The return value depends on the state of the statement that was last executed before the end of the script execution;

$@, $*: all positional parameters;
$#: Number of positional parameters;
$: script Name

Two, if statement

1. Single Branch if statement:
Format:
if condition; Then
Statement 1
Statement 2
...
Fi
Example 3, write a script to achieve the following functions: If the user exists, it means that the existence;

Copy Code code as follows:

#!/bin/bash
Username=user1
If grep "^ $UserName \>"/etc/passwd &>/dev/null; Then
echo "$UserName exists."
Fi

Example 4, write a script to achieve the following functions: If the device/dev/sda3 has been mounted, display its mount point;
Copy Code code as follows:

#!/bin/bash
Device= '/dev/sda3 '
If Mount | grep "^ $Device" &>/dev/null; Then
Mount | grep "/dev/sda3" | Cut-d '-f3
Fi

Example 5, write a script to achieve the following functions: If there is a blank line in the/etc/rc.d/rc.sysinit, it shows the number of blank lines;

Copy Code code as follows:

#!/bin/bash
File= '/etc/rc.d/rc.sysinit '
If grep "^$" $File &>/dev/null; Then
grep "^$" $File | Wc-l
Fi

2, Double branch if statement:

Format:
if condition; Then
Statement 1
Statement 2
...
Else
Statement 1
Statement 2
...
Fi

Example 6, write a script to achieve the following functions:

If the device/dev/sda3 is already mounted, the mount point is displayed, otherwise, it is not mounted or the device does not exist;

Copy Code code as follows:

#!/bin/bash
Device= '/dev/sda3 '
If Mount | grep "^ $Device" &>/dev/null; Then

Mount | grep "/dev/sda3" | Cut-d '-f3
Else
echo "$Device not mounted or not exist."
Fi

3, multiple branch if statement:
Format:
If condition 1; Then
Statement 1
Statement 2
...
Elif Condition 2; Then
Statement 1
Statement 2
...
elif condition 3; Then
Statement 1
Statement 2
...
Else
Statement 1
Statement 2
...
Fi
Example 7, write a script:
Determine the CPU manufacturer for the current host, with information in the Vendor ID row in the/proc/cpuinfo file.
If its manufacturer is Genuineintel, it is Intel Corporation;
If its manufacturer is AUTHENTICAMD, it will show AMD company;
Otherwise, the display is not recognizable;

Copy Code code as follows:

#!/bin/bash
Vendor= ' grep ' vendor_id '/proc/cpuinfo | Uniq | cut-d:-f2 '
if [[$Vendor =~ [[: space:]]*genuineintel$]]; Then

echo "Intel"
elif [$Vendor =~ [[: space:]]*authenticamd$]]; Then
echo "AMD"
Else
echo "Unknown"
Fi

Lower:

One, bash condition test:
Integer test [expression]
character test [[expression]]
Conditional testing test expression Test returns 0 (true) or 1 (false) as a result of an expression evaluation

1. Integer test: Numerical comparison
-GT Greater than
-ge is greater than or equal to
-eq equals
-lt less than
-le less than or equal to
-ne is not equal to

Example 1: Write a script that generates two random numbers, compares their size, and displays large numbers;

Bash has a built-in variable: $RANDOM

Copy Code code as follows:

#!/bin/bash
A= $RANDOM
b= $RANDOM
If [$A-ge $B]; Then
echo "Max number is $A."
Else
echo "Max number is $B."
Fi

Example 2: Write a script, randomly generate an integer, determine, show its parity;

Copy Code code as follows:

#!/bin/bash
#
A= $RANDOM
If [$[$A%2]-eq 0]; Then
echo "$A: Even"
Else
echo "$A: Odd"
Fi

Example 3, write a script:

Calculate the sum of all odd numbers and all even number within 100, and show them separately;

Copy Code code as follows:

#!/bin/bash
Evensum=0
Oddsum=0
For I in {1..100}; Todo
If [$[$I%2]-eq 0]; Then
evensum=$[$EvenSum + $I]
Else
oddsum=$[$OddSum + $I]
Fi
Done
echo "Evensum is: $EvenSum. Oddsum is: $OddSum. "

Example 4, to compute the sum of all odd numbers and all even in N, and to show that n is a positive integer passed through the parameter;

Copy Code code as follows:

#!/bin/bash
Evensum=0
Oddsum=0
For I in ' seq 1 $ ';d o
If [$[$I%2]-eq 1]; Then
oddsum=$[$OddSum + $I]
Else
evensum=$[$EvenSum + $I]
Fi
Done
echo "Evensum: $EvenSum."
echo "Oddsum: $OddSum."
echo "Sum: $[$EvenSum + $OddSum]"

Example 5, write a script to complete the following requirements:

1, add 10 users user1, User2, ..., User10, but first to determine whether the user exists, does not exist and then add;
2, after the completion of the addition, the display has added a total of several users, of course, can not be included because of prior existence without adding;
3, the final display of the current system on a total number of users;

Copy Code code as follows:

#!/bin/bash
Count=0
For I in {1..10}; Todo
If ID user$i &>/dev/null; Then
echo "user$i exists."
Else
Useradd user$i
echo "Add user$i successfully."
count=$[$Count +1]
Fi
Done
echo "Add $Count new users."
echo "Total users: ' Wc-l/etc/passwd | Cut-d '-f1 '.

2. Bash character test:
": Greater Than
: Less than
= =: equal To
=~: Determines whether the string on the left can be matched by the pattern on the right, usually used [[]];
[[$opt 1 =~ $opt 2]]] generally do the beginning of the line, the end of the anchor; do not quote
Monocular:
-Z $STRING: null is true, not empty is false;
-N $STRING: null is false, not empty is true;

Example 6, write a script to determine whether the user's shell is bash;

Copy Code code as follows:

#!/bin/bash
Shell= ' grep ' ^$1: "/etc/passwd | cut-d:-f7 '
If ["$Shell" = = "/bin/bash"]; Then
echo "Bash User."
Ret=0
Else
echo "Not Bash User."
Ret=9
Fi
Exit $Ret

Example 7, according to the user shell terminator is sh to determine whether it is a logged-on user:

Copy Code code as follows:

#!/bin/bash
Shell= ' grep ' ^$1: "/etc/passwd | cut-d:-f7 '
If [-Z $Shell]; Then
echo "No shell."
Exit 3
Fi
if [["$Shell" =~ sh$]]; Then
echo "Login User."
Ret=0
Else
echo "None Login User."
Ret=4
Fi
Exit $Ret

Second, bash test file test:

Operator file path
-F: Test whether it is a normal file, that is, ls-l file type-file;
-D: Test whether it is a directory file, that is, ls-l file type D file;
-e: Test file exists, exists as true, otherwise false;
-R: Tests whether the file is readable to the current user;
-W: Test file is writable for the current user;
-X: Test whether the file is executable for the current user;
-S: Test file size is not empty, is true, empty is false;
Short-circuit operation: As long as the first half of the final paragraph can be determined, the second half of the operation is no longer;
and operations:
True && true = True
True && false = False
False && {true | false} = FALSE


OR operation:
Fake | | 0 = 0
Fake | | 1 = 1
true | | =1

Example 8, given a path, judge if it is a normal file, show it;
Otherwise, say cannot recognize;

Copy Code code as follows:

#!/bin/bash
if [!-e $]; Then
echo "No such file."
Exit 7
Fi
If [F $]; Then
echo "Common file."
elif [D $]; Then
echo "Directory."
Else
echo "Unknown file."
Fi

Comprehensive Example:
Write a script: You can accept a parameter with the following form:
script.sh {Start|stop|restart|status}
If the argument is start, create an empty file/var/lock/subsys/script and display "starting script successfully." ;
If the argument is stop, the file/var/lock/subsys/script is deleted and the Stop script finished is displayed. ;
If the parameter is restart, the file/var/lock/subsys/script is deleted and the restarting script successfully is displayed. ;
If the parameter is status, then:
If the/var/lock/subsys/script file exists, it is displayed as "the script is running."
Otherwise, it is displayed as "The script is stopped."
Any other parameter: "script.sh {start|stop|restart|status}" is displayed

Copy Code code as follows:

#!/bin/bash
If [$ = start]; then
Touch/var/lock/subsys/script
echo "Starting script successfully."
elif [$ = stop]; Then
Rm-f/var/louk/subsys/script
echo "Stop script finished."
elif [$ = = Restart];then
Rm-f/var/louk/subsys/script
Touch/var/lock/subsys/script
echo "Restarting script successfully."
elif [$ = = Status];then
[-e/var/lock/subsys/script]&& echo "script is running." | | echo "Script is stopped."
Else
echo "script.sh {start|stop|restart|status}"
Fi

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.