Shell scripting basics, using variables, conditional testing and selection, list loops

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

[Basic Shell Scripting]

<<Shell Environment>>

<Shell scripting concept>
Design executable statements in advance, files used to complete specific tasks
--interpreted programs
--sequential, batch execution
Common scripting language
Bash Shell
Python/Perl/Rudy
JSP/PHP/ASP/CGI
JavaScript

<How to use Bash Shell>
Interactive
--manual intervention, high degree of intelligence
--explanation and execution one by one, low efficiency
Non-interactive
--need to design in advance, high degree of intelligence
--batch execution, low efficiency
--convenient for background quiet The general composition of running a
standard shell script
#!/bin/bash Environment declaration (Sha-Bang)
# Comment text
Executable code
<The first shell script>
Script creation process
1) Clear task requirements
--split small steps by natural language
--Organize in order
2)Write code files
--How to implement each step
--Convert to command line and save to script file
3)Test and improve
--Run script to eliminate errors
--Code optimization

Script running and debugging
1) Write a script
vim /root/sysinfo
--->
#!/bin/bash
cat /etc/redhat-release
uname -r
hostname
2) Add execute permission
chmod +x /root/sysinfo
3) Run the test
/root/sysinfo
--->
Red Hat Enterprise Linux Server...
3.10.0-123.el7.x86_64
server0.example.com
4) Check and troubleshoot
sh -x /root/sysinfo
--->
+ cat /etc /redhat-release
Red Hat Enterprise Linux Server...
+ uname -r
3.10.0-123.el7.x86_64
+ hostname
server0.example.com
[Simple script trick]
Pipeline passing
the output of the previous command to the next one Command processing command1 | command2
[|command3]
ls --help | less pass multiscreen text
Interaction-free processing
Log valuable information >> /var/log/foo.log Append
Shield worthless and disturbing information &> /dev/null black hole file
Customize output echo 'text string'
redirect output
standard Output (1): Normal result
Standard error (2): Error or abnormal result The
output result is saved to the file
cmd > file, cmd >> file
cmd 2> file, cmd 2 >> file
cmd &> file Correct errors are recorded in
cmd 1 > file 2>&1 correct errors are wrong
cmd 2> file 1>&2 correct errors are wrong
1>&2, >&2 standard output--->standard error
2>&1 standard error--->standard output

[Use variables]
Definition of
variables Variable name = variable value
Fixed name replaces value, "passing parameters"
reduces the amount of code
When assigning
1) The variable already exists, overwriting the original value
2) = No spaces on both sides
3) Variable name composition: abc, 123 , _, case sensitive
4) Cannot start with a number, cannot use keywords, special characters
Basic format
Reference variable value: $variable name
View variable value:
echo $variable name, echo ${variable name}
var=CentOS var7.2 =CentOS2
echo $var ---> CentOS
echo $var6.7 ---> CentOS6.7
echo $var 7.2 ---> CentOS7.2
echo ${var}7.2 ---> CentOS2 delimit obfuscated names with {}
[Variable types]
1) Environment variable The
variable name is capitalized, used to set the user/system environment
PWD, PATH, USER, LOGNAME, SHELL, HOME
2) The location variable is
built-in in bash, and stores the command line parameters provided when executing the script
$nn=1 , 2, 3...
3) The predefined variables are
built-in in bash, used directly, and cannot be directly assigned.
Used to save the execution information of the script program
$# The number of loaded position variables
$* The value of all position variables
$? The status value after the program exits, 0 means normal, other values ​​are abnormal
4) User-defined variables
Set by the user
[special variables use trilogy]
1. Write the script code
vim /root/useradd
--->
#!/bin/bash
echo "A total of $# parameters are provided"
echo "Successfully added user $1, the password is $2 "
useradd $1
echo "$2" | passwd --stdin $1
2. Add x execution permission
chmod +x /root/useradd.sh
3. Add user and password, and test
/root/useradd kenji 123
--->
A total of 2 parameters are provided.
Successfully added user kenji, the password is 123
Change the password of user kenji
passwd: all Authentication token has been successfully updated


Conditional test and selection
[Conditional test]
Shell test basis
Command line/program exit status value $?
value = 0, successful execution
Value is not 0, failure/abnormal
Script exit status value: $? of the last command before exit
can also be used by yourself Replace, add exit integer
Test operation
Normal command line
tsxt -option parameter
[test expression]
id fleyd &> /dev/null Test operation
echo $? ---> 1 Status value is 1, indicating failure
[100 -gt 50] Test expression
echo $? ---> 0 The status value is 0, indicating success
Common test options
check file status
-e document
-d directory
-f exist
-r read
-w writable
-x execute
compare integer size
-gt grent than greater than
-ge greater than or equal to
-eq equal to
-ne not equal to
-lt less than
-le less than or equal
String comparison
- == != ! Negate

[if selection structure]
if single-branch
if ... ;then ...
fi
if double-branch
if ... ;then ...
else ...
fi
if multi-branch
if ... ;then ...
elif .. . ;then ...
else ...
fi
list loop
[for loop structure]
traversal/list loop
for variable name in value list for variables in the list...
do .. do... process
done done
$( Command line)
first execute the parentheses, and then use the value as an external command to execute the parameter
cat /root/userlist
--->
haha
​​xixi
kenji
echo $(cat /root/userlist)
--->
haha ​​xixi kenji
[Write a batch add user script]
1. Write script code
vim /root/batchusers
--->
#!/bin/bash
if [ $# -eq 0 ]
then
echo "Usage:/root/batchusers <userfile>"
exit 1
fi

if [ ! -f $1 ]
then
echo "Input file not found"
exit 2
fi

for name in $(cat $1)
do
useradd -s /bin/false $name
done
2. Add x execute permission
chmod +x /root/batchusers
3. Test script
1) Prepare file
wget http://classroom/pub/materials /
userlist -O /root/userlist
2) Add users in batches
/root/batchusers /root/userlist
3) Test
/root/batchusers No list file provided
---> Usage: /root/batchusers <userfile>
echo $? -- -> 1
/root/batchusers /root/userlist.txt
---> Input file not found The provided list file cannot find
echo $? ---> 2

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324929644&siteId=291194637