I. Shell environment and features 1.1 what is a shell
Interpreter: Responsible for translating and communicating user/program instructions to the kernel
Interpreter car
Shell car
Bash BMW, Mercedes, Ferrari
1.1.1/etc/shells
The content inside the file is the system-installed interpreter.
1.1.2 Usermod-s/bin/tsh Zhangsan
Modify the default interpreter for old users
1.1.3 Useradd-s/bin/tsh Zhangsan
Specify the default interpreter when creating a new user
1.2 Bash Basic features 1.2.1 shortcut keys
Ctrl+l Clear Screen
CTRL + C terminates the currently running program
CTRL + A moves the cursor to the beginning
Ctrl+e move cursor to end of line
Ctrl+w Delete one word before the current cursor
Esc+d Delete A word after the current cursor
Ctrl+u Delete all content from the current cursor to the beginning of the line
Ctrl+k Delete all the contents of the current cursor to the end of the line
Ctrl+f move forward one character
Ctrl+b Move backward one character
Alt+b move forward one word
Alt+f Move backward One word
1.2.2 Tab key Completion
RHEL7.2 only supports the completion option, the old version is available through the Bash-completion package with options
1.2.3 Command History
grep histsize/etc/profile# View History Command Save the number of bars by default
History | wc-l# See how many commands are currently in use
!100# Execute 100th Order
!cat# from back to front to find the most recently executed cat command
history-c# Clear History Command
~/.bash_history
1.2.4 Command Aliases
Alias
Unalias
/etc/bashrc
~/.bashrc
1.2.5 standard input and output
Standard output &1
Error Output &2
Standard input &0
1.2.6 Redirection
For scripting, redirection is very important, which is equivalent to logging a script for execution
1> correct output 1>> correct append output
2> Error Output 2>> error append output
&> redirect normal output, error output to the same file
/dev/null 2>&1 is equivalent to 1>/dev/null 2>/dev/null. is to redirect standard error to standard output, and the last & to take standard devices.
Echo ' ERROR ' >&2 redirects the echo-out result to the error output.
< REDIRECT input
1.2.7 Pipeline Operation
Inside the Linux pipeline is very important!!!
Use the output of the previous command as input to the following command
Because the Linux command design principle is 3S (simple, small, speed), the larger the software startup slower, the more vulnerable. Piping is used specifically to combine multiple commands to achieve complex functions
Yum List|grep abc|wc-l
echo "Content" | Mail-s "title" Receipt disadvantage is that the message content can not be written too much, the advantage is not to create additional files
Mail-s "title" Receipt < Mail.txt disadvantage is the need to create a file first, the advantage is that you can write a lot of content
Second, shell script design 2.1 new file
Extension is. sh
2.2 Write code
Shelf the first line must be #!/bin/bash, indicating that the script specifies that bash is used as the script interpreter
#为注释符, notes can write time, version, feature, contact
2.3 Giving permission
chmod +x Foot Name
2.4 Execute Script
./script Name # relative path
/root/Script Name # Absolute path
Bash Script Name # Specifies the interpreter, even if the script does not have EXECUTE permission, can also execute the script
The above execution mode will open the child process
But watch out! The source script name does not open a child process.
In a special case, for example, there is only one line exit in the script, and the current bash is exited after executing the script
$PATH Command Search Path
Iii. Script 3.1 Print out Hello the world
#!/bin/bash
echo "Hello the word"
3.2 Configuring the Yum source automatically
#!/bin/bash
if [-D/ETC/YUM.REPOS.D];then
rm-fr/etc/yum.repos.d/*
Echo ' [DVD]
Name=rhel
Baseurl=http://192.168.4.254/rhel7
Gpgcheck=0 ' >/etc/yum.repos.d/dvd.repo
Else
Mkdir-p/etc/yum.repos.d/
Echo ' [DVD]
Name=rhel
Baseurl=http://192.168.4.254/rhel7
Gpgcheck=0 ' >/etc/yum.repos.d/dvd.repo
Fi
3.3 Automatic Installation VSFTPD
#!/bin/bash
Yum Clean all >/dev/null
Yum-y Install vsftpd 2>/var/log/ins_vsftpd_err.log >/dev/null
Systemctl Restart vsftpd && systemctl enable VSFTPD >/dev/null
3.4 Creating User Scripts
#!/bin/bash
Read-p "Please enter user name:" Name
#关闭回显
Stty-echo
Read-p "Please enter your password:" Pass
#打开回显
Stty Echo
Useradd $name
echo $pass | passwd--stdin $name
3.5 Backup/var/log per Friday, use tar to back up to/root directory
Echo ' 5 tar-czf/root/log-$ (date+%f). Tar.gz/var/log ' >>/var/spool/cron/root
3.6 per minute detection of the number of users logged on at the current computer, if greater than 2, send an email alert
Idea: How to detect the number of login users? How to judge more than 2? How do I send an email?
#!/bin/bash
#判断本机登录的用户数是否大于2, if it is greater than 2, send the message to root
num=who|wc -l
[$num-gt 2] && mail-s Error root </root/mail.txt
#mail. txt is the message content to be sent
3.7 Determine if there is a CD directory to mount the disc; Create a directory and mount the disc without a CD directory
[-D/ROOT/CD] && MOUNT/ISO/RHEL7.ISO/CD | | Mkdir/cd;mount/iso/rhel7.iso/cd
[-D/ROOT/CD] | | MKDIR/CD && MOUNT/ISO/RHEL7.ISO/CD
[!-D/ROOT/CD] && MKDIR/CD;MOUNT/ISO/RHEL7.ISO/CD
3.8 Calculation of the 1+2+3+4...+100 and
Idea: Only care about the last draw and. How to Output 1: 100? The value of the output is stored in another variable? The other variable stores the last derived and
#!/bin/bash
J=0
For i in {1..100}
Do
Let J+=i
Done
Echo $j
3.9 Each file under the/var/log, individually packaged, saved to/TMP
Idea: How to display each file? How do I pack and save?
#!/bin/bash
For N inls /var/log
Do
tar-zcf/tmp/$n. tar.gz/var/log/$n &>/dev/null
Done
3.10 Enter the number sum until the input 0 ends and the output and
Idea: Read keyboard input? Sum and exist in another variable? If input 0 ends the loop and outputs and
#!/bin/bash
Result=0
While:
Do
Read-p "Please enter a number [0 end]:" NUM
[$NUM-eq 0] && break
Let result+= $NUM
Done
Echo $RESULT
3.11 Printing 9*9 Multiplication table
Actual screen output:
11=1
21=2 22=4
31=3 32=6 33=9
......
91=9 92=18 93=27 94=36 95=45 96=54 97=63 98=72 9*9=81
Idea: i={1..9} j={? To strike a triangle, the core is I<=j
Script:
#!/bin/bash
For j in {1..9}
Do
For i in {1..9}
Do
Echo-en "$i$j =$[ij]\t"
[$i-eq $j] && break
Done
Echo
Done
#!/bin/bash
For j in {1..9}
Do
For I inseq $j
Do
Echo-en "$i$j =$[ij]\t"
Done
Echo
Done
3.12 Print Chess chessboard (8*8)
Idea: The checkerboard format is black and white
Script:
#!/bin/bash
For n in {1..4}
Do
For i in {1..4}
Do
Echo-en "\033[44m \033[0m"
Echo-en "\033[45m \033[0m"
Done
Echo
For j in {1..4}
Do
Echo-en "\033[45m \033[0m"
Echo-en "\033[44m \033[0m"
Done
Echo
Done
More Excellent code:
#!/bin/bash
Color () {
For n in {1..4}
Do
Echo-en "\033[4$1m \033[0m"
Echo-en "\033[4$2m \033[0m"
Done
}
For i in {1..8}
Do
Y=$[I%2]
[$y-eq 1] && color 7 0 | | Color 0 7
Echo
Done
3.13 of monkeys picked n bananas. The 1th day ate half, did not eat a full and ate one, the 2nd day ate half again, did not eat a full and ate one; There are only 1 bananas left on the 9th day of eating. May I ask N for a few?
Idea: The number of previous day y equals today's Quantity (x+1)2
X=1
For i in {1..8}
x=$[(x+1)2]
3.14 Prompts the user to display a sum of a number, enter any number, then output any number of sums; If you do not enter a value, the display 1+ ... 100 of and
Idea: How to calculate 1+...x's and? How do I handle a value without entering it?
#!/bin/bash
Sum=0
Read-p "Please enter a number:" num
NUM=${NUM:-100}
For I inseq $num
Do
Let Sum+=i
Done
echo "Sum value from 1 to ${num}: $sum"
Exit
3.15 The computer randomly generated 3 numbers, the 3 numbers from small to large output to
Idea: NUM1 minimum value, num2 in the middle, num3 Maximum, tmp as the intermediate variable. How many kinds of possibilities are there?
Num1>num2>num3
num1< num2< num3
Num2 < num3
Num2
First if judging num1 and num2 ratio size. If the NUM1 large, then the NUM1 and num2 exchange, to ensure that the NUM1 store is a small value, if the num2 is large, then do not operate, end this judgment
And then one more if Judge Num1 and num3 size. If the NUM1 large, then the NUM1 and num3 exchange, to ensure that the NUM1 storage is the minimum value, if the num3 is large, then do not operate, end this judgment
The last if Judge num2 and num3 ratio size. If the num2 large, then the num2 and num3 exchange, to ensure that the NUM3 storage is the maximum value, if the num3 is large, then do not operate, to end this judgment.
From small to large output $NUM1 $num 2 $num 3
#!/bin/bash
#num1存最小值, num2, num3 deposit maximum
num1= $RANDOM
Num2= $RANDOM
num3= $RANDOM
Tmp=0
If [$num 1-gt $num 2];then
tmp= $num 2;num2= $num 1;num1= $tmp
Fi
If [$num 1-gt $num 3];then
tmp= $num 1;num1= $num 3;num3= $tmp
Fi
If [$num 2-gt $num 3];then
tmp= $num 3;num3= $num 2;num2= $tmp
Fi
echo $num 1 $num 2 $num 3
Iv. variables
Store values that may change with a fixed name
4.1 Defining rules
If the specified variable name exists, it is equivalent to assigning a value to the variable
Cannot have spaces on either side of the equals sign
Can only be made up of numbers, letters and underscores
Cannot start with a number
4.2 Assignment Value 4.2.1 Direct Assignment
Variable name = variable Value
from=/etc/
4.2.2 getting variable values through read
READ-P "hint" variable name # defines only the variable name and does not assign a value. Assigned by the person using the command
4.2.3 using command-line arguments
Use positional variables $, $, etc.
Output of the 4.2.4 pipeline receive command
by pipe | The output of the preceding command as input to the current command
4.3 references
$FROM
4.4 views
Echo $FROM
Echo ${from}
4.5 Environment variables
Configuration files:/etc/profile, ~/.BASHRC
PATH
HOME
USER
Uid
HOSTNAME
PS1 level prompt
PS2 Level Two prompt
4.6 Pre-defined variables
$: The name of the script itself
$: Position Variable 1
$: Position Variable 2
$: All variables
$ @: all variables.
$ and [email protected] All represent all parameters passed to a function or script, and are not enclosed by double quotation marks (""), with "$" and "$" ... All parameters are output in the form "$n".
But when they are enclosed in double quotation marks (""), "$*" takes all the parameters as a whole and outputs all parameters in the form of "$ $ ... $n"; "[email protected]" separates the various parameters to "$" "$" ... All parameters are output in the form "$n".
$#: The number of all variables
$$: The PID after the script is run
$!: Shows the last process PID that was put into the background
$?: previous command execution state, value equal to 0 is correct, value not 0 is error
4.7 Local variables and global variables 4.7.1 local variables
Custom variables are local variables by default
Variables that exist in script functions (function) are also local variables.
To declare with the local variable name so that it is only valid within the scope of this function, prevent the variable from being named in the function and the name of the variable in the variable external program causes the program exception.
Local variables are only valid in the current shell environment by default and cannot be used in child shell environments
Local variables can be declared as global variables through the Export command
4.7.2 Global Variables
System variables are global variables by default
Global variables are valid in the shell environment of the current shell environment and the child, grandchild, etc.
/etc/profile
Export variable name # Declare a local variable as a global variable
Export-n variable name # Cancel declaration
Five, single quotes & double quotes & Inverted quotation marks 5.1 double quotes ""
Double quotes can define a complete string
echo a B
echo "A B"
5.2 Single Quote "'
Single quotation marks can be used to define a complete string, and the special symbol ($\) can be masked and output intact.
5.3 Anti-quote "'
命令
Only commands can be placed, the result of the command is extracted
$ (command) can only be placed command, extracted is the result of the command
DAY01 Shell Script Programming