Shell scripting basics, using variables, conditional testing and selection, and list-looping

Source: Internet
Author: User
Tags stdin yum repolist

##################################################################################################
Shell script:
Scripts: Files that can be executed, implemented after running a certain function (command stacking, interactive)

Standardize the general composition of shell scripts:
#! Environmental statement
# comment Text
Executable code

###############################################################################################
One. Write the first script program
#vim/root/1.sh
#! /bin/bash
echo "Hello World"//Output Hello World
Hostname//Output host name
Ifconfig | HEAD-2//Output NIC information first two lines
Cat/etc/redhat-release//output system version information
#chmod +x/root/1.sh//Give File execution permissions
#/root/1.sh//Execute script
Hello Word
Server0.example.com
Eth0:flags=4163<up,broadcast,running,multicast> MTU 1500
inet 172.25.0.11 netmask 255.255.255.0 broadcast 172.25.0.255
Red Hat Enterprise Linux Server Release 7.0 (MAIPO)//Output results

##################################################################################################

Two. Write a script that automatically builds Yum for Server0
#vim/root/yum.sh//Create a script program file
#! /bin/bash
Echo ' [Rhel]//yum Warehouse Information
Name=rhel//yum Warehouse Name
baseurl=http://172.25.254.254/content/rhel7.0/x86_64/dvd///Network Yum Source Address
enable=1//boot auto-load
Gpgcheck=0 ' >/etc/yum.repos.d/rhel.repo//No signature authentication, redirect these content to a file/etc/yum.repos.d/rhel.repo
#yum clean all//empty cache
#yum repolist//view Yum Package information
#chmod +x/root/yum.sh//Give Execute permission
#/root/yum.sh//Execute script loaded plugin: langpacks
Cleaning up software Source: Rhel
Cleaning up everything
Loaded plugins: langpacks
Rhel | 4.1 KB 00:00
(a): Rhel/group_gz | 134 KB 00:00
(2/2): rhel/primary_db | 3.4 MB 00:00
Source Identity Source Name status
Rhel Rhel 4,305
repolist:4,305//Run successfully


###############################################################################################################

Pipeline delivery:
Pipeline operation: The standard output of the previous command is referred to the next command for processing.

Non-interactive and output processing:
No interaction: Scripts are typically performed in the background, to reduce the manual interaction of statements

Script Output Information Processing:
Record valuable information (>>/var/log/foo.log)
Masking of worthless, disruptive information (&>/dev/null)
User-definable output: Echo ' text string '

REDIRECT output:
Standard output: Command execution normal is display result
Standard error: Display results when a command performs an error or an exception

To save the screen information to a file:
> collect the correct output into a file
2> to collect the error output into a file
&> collect the correct and error outputs from the previous command
>&2 changing the correct output of the command to an error output

# echo 123 >/opt/a.txt
# CAT/OPT/A.TXT/ETC
123//correct output
Cat:/etc: is a directory//error output
# cat/opt/a.txt/etc >/opt/b.txt//Collect the correct output only
Cat:/etc: is a directory
# cat/opt/a.txt/etc 2>/opt/b.txt//Only error output is collected
123
# cat/opt/a.txt/etc &>/opt/b.txt//correct and error outputs are all collected

############################################################################################################### ##

Three. Write a script that creates a user and sets a password:
# vim/root/user.sh

#!/bin/bash
Useradd test06 &>/dev/null
Echo Test06 created successfully
Echo 123 | passwd--stdin test06 &>/dev/null
echo test06 Password Setup succeeded

# chmod +x/root/user.sh
#/root/user.sh

############################################################################################################### ##

Variables: To increase the ability of the script to adapt to the environment, increase the flexibility of the script, convenient.
Variable: the equivalent of a container, with a constant name, to store the changed values.
Variable name = changed value

Use variable: $ variable name


To reduce the difficulty of using scripts, you can create interactive
READ: Can generate interaction to assign the contents of the keyboard input to a variable

#vim/root/user.sh
Read-p "Please enter the user you want to create:" User//user is the username variable
Read-p "Please enter the password you want to set:" Pass//pass is the user password variable
Useradd $user &>/dev/null//correct and error messages are all collected in/dev/null
Echo $user created successfully
echo $pass | passwd--stdin $user &>/dev/null
echo $user Password Setup succeeded
#/root/user.sh
Please enter the user you want to create: Lala
Please enter the password you want to set: 12
Lala created successfully
Lala Password Setup succeeded

#######################################################################

What is a variable
Values that are stored as immutable names that may vary
– Variable name = variable Value
– Easy to reuse a value with a fixed name
– Improved adaptability to mission requirements and operational environment changes


Considerations when setting a variable
– If the specified variable name already exists, it is equivalent to re-assigning a value to this variable
– Don't have spaces on both sides of the equals sign
– Variable names are made up of letters/numbers/underscores, case-sensitive
– Variable names cannot start with a number, do not use keywords and special characters


Basic format
– Reference variable Value: $ variable Name
– View variable values: Echo $ variable name, echo ${variable name}


Types of variables



Positional variables
Command-line arguments (non-interactive pass-through values) that are provided when the script is executed

[Email protected] ~]# vim/root/2.sh
#!/bin/bash
echo $
Echo
echo $
Echo ${10}
Echo ${11}

#/root/2.sh haha benniu xixi hehe lele DC TC DZ TZ 100 200

[Email protected] ~]# vim/root/3.sh
#!/bin/bash
Cat-n $ | Head-$2

[Email protected] ~]#/ROOT/3.SH/ETC/PASSWD 2
[Email protected] ~]#/ROOT/3.SH/ETC/PASSWD 3



Pre-defined variables
The execution information used to save the script
– Use these variables directly
– You cannot assign values directly to these variables

$# the number of position variables that have been loaded
$* values for all positional variables
$? Status value after program exit, 0 indicates normal, other value is abnormal



[Email protected] ~]# vim/root/2.sh

#!/bin/bash
echo $
Echo
echo $
Echo ${10}
Echo ${11}
Echo $#
Echo $*

[[email protected] ~]#/root/2.sh 1 2 3 4 5 6 7 8 9 10 11


########################################################
Operation

[[email protected] ~]# expr 10/3

[[email protected] ~]# Expr 10 \* 3

[[email protected] ~]# Expr 1 + 2

[[email protected] ~]# expr 3-1

[[email protected] ~]# Expr 3 #取余数 operation

$ (): The output of the command, as a parameter

[[Email protected] opt]# Date
[Email protected] opt]# date +%f
[Email protected] opt]# cd/opt

[[email protected] opt]# mkdir $ (date +%f)
[[email protected] opt]# ls
[Email protected] opt]# mkdir mydir-$ (date +%f)
[[email protected] opt]# ls
[Email protected] opt]# mkdir mariadb-$ (date +%f)
[[email protected] opt]# ls
[[email protected] opt]# mkdir $ (hostname)-$ (date +%f)

#######################################################
Common Test Options

Check file status
-e: Document exists as true
-D: Document exists and is directory-True
-F: Document exists and is file-true
-r: Document exists with Read permission true
-W: Document exists with Write permission true
-X: Document exists with Execute permission true

Compare integer size (with E equals two words, g means greater than, L is less than)

-GT: Greater Than
-ge: greater than or equal to
-eq: Equals
-ne: Not equal to
-LT: Less than
-le: Less than or equal to

string alignment
= =: Equal
! =: Not Equal


########################################################



If [condition test]; Then
Command sequence XX
Else
Command Sequence yy
Fi

[Email protected]/]# vim/root/5.sh
#!/bin/bash
If [$1-eq $];then
echo Hello
Else
echo Hi
Fi

[Email protected]/]#/root/5.sh 1 1

[Email protected]/]#/root/5.sh 1 2

###########################################################################################################

Please write a script:
The user enters an IP address (read) to determine if it can communicate with the IP address.
Can output "IP OK" otherwise output "IP No"

[Email protected]/]# vim/root/6.sh

#!/bin/bash
Read-p ' Please enter an IP address: ' IP
Ping-c 2 $ip &>/dev/null

If [$?-eq 0];then
Echo ${ip} OK
Else
Echo ${ip} No
Fi

[Email protected]/]#/root/6.sh

##########################################################################################

If [condition test 1]; Then
Command sequence XX
elif [condition Test 2]; Then
Command Sequence yy
Else
Command Sequence ZZ
Fi


Score greater than or equal to 90 excellent
Greater than or equal to 80 good
Greater than or equal to 70 pass
Greater than or equal to 60 still requires effort
60 below in the cattle of Chopin, also can not play the elder brother Sadness




[Email protected] ~]# vim/root/8.sh
#!/bin/bash
Read-p ' Please enter your score: ' num
If [$num-gt];then
Echo score is wrong
elif [$num-lt 0];then
Echo score is wrong
elif [$num-ge];then
Echo Excellent
elif [$num-ge];then
echo Good
elif [$num-ge];then
Echo Pass.
elif [$num-ge];then
Echo still needs to work hard
Else
echo in the Ox Chopin, also can not play the elder brother Sadness
Fi

########################################################################################################### #3

Create a/root/foo.sh script on Server0
1) When running/root/foo.sh Redhat, the output is Fedora
2) When running/root/foo.sh fedora, output is Redhat
3) when no parameters or parameters are not redhat or
When fedora, its error output produces the following information:
/root/foo.sh Redhat|fedora







": The output of all special characters as normal text characters

[Email protected] ~]# vim/root/foo.sh
#!/bin/bash
if [= = = Redhat];then
echo Fedora
elif [= = = Fedora];then
Echo Redhat
Else
Echo '/root/foo.sh Redhat|fedora '
Fi

[Email protected] ~]#/root/foo.sh Redhat
[Email protected] ~]#/root/foo.sh Fedora

[Email protected] ~]#/root/foo.sh haha

The problem: When the user does not enter any parameters, the expression does not hold, because the expression if [= = = = Redhat];then, equivalent to if [= = Redhat];then, equivalent to Redhet in a non-existent variable in the comparison; The reach of the type is not established.



#!/bin/bash
If [$#-eq 0];then
Echo '/root/foo.sh Redhat|fedora '
elif [= = Redhat];then
echo Fedora
elif [= = = Fedora];then
Echo Redhat
Else
Echo '/root/foo.sh Redhat|fedora '
Fi

There is a problem: the error output represented in the title is:/root/foo.sh Redhat|fedora. But, as we run this script, root/foo.sh Redhat|fedora is the correct output, so we're going to turn root/foo.sh Redhat|fedora into an error output.

>&2 #将正确输出变成错误
"": You can Change "no" to "null"


#!/bin/bash

If ["$" = = Redhat];then
echo Fedora
elif ["$" = = Fedora];then
Echo Redhat
Else
Echo '/root/foo.sh Redhat|fedora ' >&2 #将正确输出变成错误
Exit 2 #脚本退出返回值
Fi

Explanation: When the user does not enter any parameters, the expression ["["] = = Redhat], equivalent to ["" = = Redhat]. Represents a null value, so it is not equal, so the output/root/foo.sh Redhat|fedora

############################################################################################################### #


For loop structure

Loop structure: The repeated execution of the statement, loop to execute


For variable name in value list
Do
Command sequence
Done




[Email protected]/]# vim/root/for.sh
#!/bin/bash
For a in 1 2 3 4 5
Do
Useradd nsd$a
Echo Nsd$a created successfully
Done

[Email protected]/]# vim/root/for02.sh
#!/bin/bash
For a in 1 2 3 4 5
Do
echo Hello
Done

############################################################################################################### ###

Case 5: Write a bulk Add user script
Create a/root/batchusers script on Server0
1) This script requires a user name list file as a parameter
2) If no parameters are provided, this script should give a hint
Usage:/root/batchusers, Exit and return the corresponding value
3) If a nonexistent file is provided, this script should give a
Show Input file not found, exit and return the corresponding value
4) New User login Shell is/bin/false, no need to set password
5) User list test file:
Http://classroom/pub/materials/userlist


# wget Http://classroom/pub/materials/userlist

[Email protected]/]# vim/root/batchusers
#!/bin/bash
If [$#-eq 0];then//$ #位置变量的数量, when no arguments are provided, the $ #为0, the expression is set
Echo ' Usage:/root/batchusers ' >&2//output Usage:/root/batchusers >&2 into error output
Exit 1//Return value 1, prompt for wrong input parameters
elif [!-F $];then
Echo ' Input file not found ' >&2
Exit 2
Fi
For a in $ (cat $)
Do
Useradd-s/bin/false $a
Echo $a created successfully
Done

##################################################



#!/bin/bash
If [$#-eq 0];then
Echo ' Usage:/root/batchusers ' >&2
Exit 1
elif [-E $];then
For a in $ (cat $)
Do
Useradd-s/bin/false $a
Echo $a created successfully
Done
Else
Echo ' Input file not found ' >&2
Exit 2
Fi

###################################################

Shell scripting basics, using variables, conditional testing and selection, and list-looping

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.