How to write a script

Source: Internet
Author: User
Tags line editor shebang

Shell script Programming

Program programming, interpreting execution, dependent on external program file running;

What the script is:
Stacking of commands;
However, many commands do not have idempotent, and it is necessary to use program logic to determine whether the operating conditions are satisfied.

Purpose of the script:
Automate common commands;
Perform system management and troubleshooting;
Create a simple application;
Processing of text or documents;

Classification of programming languages
Depending on the mode of operation:
Compile-and-run: Source code--compiler (compile)---Program Files
Explanation Run: Source code--run-time start interpreter, run by interpreter side interpreter side

Depending on whether the implementation of the functionality in the programming process is calling the library or calling the external program file:
Shell script Programming:
Programming with commands and programming components on the system;
Full programming:
Programming using a library or programming component;

How to compile the program:
dynamic link;
static compilation;

According to the programming model:
programming languages;
Object-oriented programming language;

program = instruction + data
Program: To organize the code with the instruction as the center, the data is to serve the code;
Sequential execution
Select Execute
When the code has only one branch: it executes when the condition is met;
Two or more branches will only execute one of the branches that meet the criteria;
Loop execution
Representative: C,bash
Object type: Organize the code with data as the center, organize the instruction around the data;
Class: Instantiate object, method;
Representative: Java,c++,python

Components of the program: Binary program files, library files, configuration files, Help files;
Binary, library file: executable file;
Library files: Can not be executed independently, can only be invoked when executed;
Configuration files, Help files: text files that can be viewed;
"The fog through the computer" and "The History of Quantum physics"

The basic structure of the programming language:
Data storage: variables, arrays
Expression: a+b
Statement: If

How to write a shell script:
The first step: use a text editor to create a text file;
Text Editor:
Line Editor: SED
Full Screen Editor: Nano,vi,vim

The first line shelf: gives the shebang, the interpreter path, indicating the interpreter program file that interprets the execution of the current script;
Common interpreters:
#!/bin/bash
#!/usr/bin/python
#!/usr/bin/perl

Add a comment with a comment beginning with #;
Indent in
Moderately add blank lines;

Blank lines in the script are ignored by the interpreter;
Except for shebang in the script, all the remaining lines beginning with # are ignored as comment lines;

Step Two: Execute the script:
The execution of a script is accomplished by running a child shell process;
(1) Give execution permission and run the program file directly; Specify the absolute or relative path of the script on the command line;
chmod +x/path/to/script_file
/path/to/script_file
Have RX permission on the script;
Have RX permission on the directory where the script resides;

(2) Run the interpreter directly and run the script as the parameter of the interpreter program;
Bash/path/to/script_file
have r permission on the script;
Have RX permission on the directory where the script resides;

(3) The dot number is used to execute a script, even if the script does not have executable permissions to run;
If you do not have execute permissions, the "./" execution will report a permission error, but the previous use of the dot number execution will not error;
#. ./99.sh

(4) The souce command can also read and execute scripts in the current environment, returning the last command in the script.
If no return value is 0, the execution succeeds, or false if execution fails.
#source 9.sh

1, write script/root/bin/systeminfo.sh, display the current host system information, including host name, IPV4 address, operating system version, kernel version, CPU model, memory size, hard disk size;
vim/root/bin/systeminfo.sh
#!/bin/bash
echo "hostname: ' hostname '"
echo "IP address is: ' Ifconfig eno16777736 | head-2 | Tail-1 | Tr-s "" | Cut-d "-f3" "
echo "OS release version: ' Cat/etc/centos-release '"
echo "kernel version: ' Uname-r '"
echo "CPU model: ' Cat/proc/cpuinfo | grep "Model Name" | Uniq | cut-d:-f2 ' "
echo "Memery size: ' Cat/proc/meminfo | Grep-i "Memtotal" | Tr-s "" | cut-d:-f2 ' "
echo "Disk size: ' Fdisk-l/DEV/SDA | head-2 | Tail-1 | cut-d:-f2 ' "

2, write the script/root/bin/backup.sh, can realize the/etc/directory backup to/ROOT/ETCYYYY-MM-DD;
vim/root/bin/backup.sh
#!/bin/bash
Cp-a/etc/root/etc ' Date +%f '

3, write the script/root/bin/disk.sh, display the current hard disk partition space utilization maximum value;
vim/root/bin/disk.sh
#!/bin/bash
DF | Tr-s "" | grep "SD" | Sort-nr-k5 | head-1 | Cut-d ""-f5

4. Write Script/root/bin/links.sh, show the IPV4 address and connection number of each remote host connecting to this host, and sort by the number of connections from large to small;
vim/root/bin/links.sh
#!/bin/bash
Netstat-tan | Tr-s "" | Cut-d ""-f5 | Grep-v ". *[[:alpha:]]\+.*" | uniq-c | Sort-r-K1
or Netstat-tan | Tr-s "" | Cut-d ""-f5 | Tail-n +3 | uniq-c | Sort-r

5, write a script to achieve the following functions:
(1) Display all files or directories in the/etc/directory that begin with uppercase p or lowercase p;
(2) Displays all the files or directories in the/var/directory itself, and converts the lowercase captions in the displayed results to uppercase and then displays;
(3) Create temporary file/tmp/myfile. XXXX;
Vim test.sh
#!/bin/bash
Ls-d/etc/[pp]*
Ls-d/var/* | Tr ' A-Z ' A-Z
Mktemp/tmp/myfile. Xxxx
chmod +x test.sh

Read command: User interaction;
Read data from the keyboard, assign to variables or arrays;
Read-p "Enter a filename:" FILE
-P ' promt ' assigns a value to the variable, outputs the prompt prompt before attempting to read, and does not wrap;
-t timeout timed out;
-a array assigns values to the arrays;

Read-t 5-p "Enter a username:" Name
[-Z "$name"] && name= "Obama"
Echo $name

Shift: Move the position parameter to the left;
Shift[n]: Position parameter rotation; Move position parameter to the left;
Assuming that the script has a,b,c three parameters, then $ a,$2 for b,$3 is C;shift once, $ b,$2 to C, and then shift once, $ c ...
Vim shift.sh
#!/bin/bash
echo "First POS Argu: $"
Shift
echo "Second POS Argu: $ $"

Exit: Exit this login;
In the script, exit represents exiting the current script, and can be followed by a numeric parameter that represents the exit status;

Break
Jump out of a loop; exit from a loop (For,while,until,select);
Break can be followed by a number n, which represents a jump out of the N-layer loop, n must be greater than 1, if n is larger than the current number of layers, then jump out of all loops;
Break:only meaningful in a "for", ' while ', or ' until ' loop
Vim break01.sh
#!/bin/bash
For I in A B C D
Do
Echo-n "$I:"
For J in ' seq 10 '
Do
If [$J-eq 5];then
Break
Fi
Echo-n "$J"
Done
Echo
Done
When the J value is 5 o'clock, the output of Break: (Loop 4 times)
A:1 2 3 4
B:1 2 3 4
C:1 2 3 4
D:1 2 3 4

Vim break02.sh
#!/bin/bash
For I in A B C D
Do
Echo-n "$I:"
For J in ' seq 10 '
Do
If [$J-eq 5];then
Break 2
Fi
Echo-n "$J"
Done
Echo
Done
Echo
When the J value is 5 o'clock, the output of Break 2 is: (1 cycles)
A:1 2 3 4

Continue
Ends the current loop and enters the next loop;
Continue can also be followed by a number n, representing the jump to the outer nth layer loop, n must be greater than 1, if n is larger than the current loop layer, will jump to the outermost loop;
Unlike break, continue does not terminate the entire loop body, it simply ends the cycle prematurely, and the entire loop body will continue to execute;
Continue:only meaningful in a "for", ' while ', or ' until ' loop
Vim continue.sh
#!/bin/bash
For I in A B C D
Do
Echo-n "$I:"
For J in ' seq 10 '
Do
If [$J-eq 5];then
Continue
Fi
Echo-n "$J"
Done
Echo
Done
When the J value is 5 o'clock, the output of the Continue is:
A:1 2 3 4 6 7 8 9 10
B:1 2 3 4 6 7 8 9 10
C:1 2 3 4 6 7 8 9 10
D:1 2 3 4 6 7 8 9 10

Vim continue.sh
#!/bin/bash
For I in A B C D
Do
Echo-n "$I:"
For J in ' seq 10 '
Do
If [$J-eq 5];then
Echo
Continue 2
Fi
Echo-n "$J"
Done
Echo
Done
When the J value is 5 o'clock, the output of continue 2 is:
A:1 2 3 4
B:1 2 3 4
C:1 2 3 4
D:1 2 3 4

#!/bin/bash
While True
Do
Read-p "SELECT 1 or 2:" num
Echo 1
Sleep 1
If [$num-eq 1];then
Continue
Fi
Echo 2
Done

#/bin/bash
While True
Do
Read-p "SELECT 1 or 2:" num
Echo 1
Sleep 1
If [$num-eq 1];then
Break
Fi
Echo 2
Done
Echo 3

How to write a script

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.