Chapter 2. Learn shell scripts

Source: Internet
Author: User

What is shell scripts?

Shell script: A shell script is a script written for shell !』

Shell script is a program written using the shell function. This program uses a pure text file to write shell syntax and commands (including external commands, it works with functions such as regular notation, pipeline commands, and data stream redirection to achieve our desired processing purpose.

Shell scripts are like batch files in the early dos era (. BAT), the simplest function is to write together many commands, this allows users to easily process complex actions using one touch (run a file "shell script" to run multiple commands at a time ).

Shell script can be regarded as a batch file or a program language. It is based on Shell and Related tool commands, so it can be run without compilation, it also has a good debugging tool.

Why Learning shell scripts?

 

  • An important basis for automated management:

    Manage the tasks that a host needs to perform every day: Query logon files, track traffic, monitor the user's status of the host, check the status of various hardware devices of the host, and check the host software upgrade. Work methods can be divided into: (1) manual processing, or (2) writing a simple program to help you automatically process analysis on a daily basis

  • Important tasks of tracking and management systems:

    The STARTUP script for services in Linux is in/etc/init. in the D/directory, all the files in the directory are scripts. In addition, the booting process also uses shell script to search for system configuration data, then, enter the configuration parameters of each service! For example, if you want to restart the system logon file, you can use: "/etc/init. d/syslogd restart". The syslogd file is a script!

    In addition, laruence once found on a generation of Fedora that MySQL database service can be started, but "failure" is always displayed on the screen 』! Later, I found out that the script that started MySQL will take the initiative to log on to MySQL with an "Empty Password", but for the sake of security, I have modified the MySQL password, later, I changed the script to solve this problem!

  • Simple Intrusion Detection:

    Most of our systems will record these abnormalities in the system recorder, which we often refer to as "system logon Files 』, then, we can take the initiative to analyze the system logon file within a fixed period of minutes. If any problem is detected, we can immediately notify the administrator or immediately strengthen the firewall configuration rules. As a result, your host can achieve "self-protection 』. For example, we can use shell script to complete "when the packet attempts several times or the connection fails, it will resist the IP address 』, for example, laruence has written a shell script to resist the hacking software!

  • Continuous command simplification:

    "It just helps us to aggregate a large string of commands into a single file, and directly run this file to run that string of smelly and long command segments !』

  • Simple data processing:

    Awk can be used to process simple data! For example, how to handle salary orders. For example, laruence once used shell script to directly process data comparison, text data processing, and so on.

  • Cross-platform support and learning experience is short:

    Almost all UNIX like above can run shell script, even MS Windows series also have related script simulator can be used, in addition, shell script syntax is quite friendly

 

The speed at which shell scripts process data is not fast. Because shell scripts use external commands and some default tools of BASH Shell, they often call external libraries. Therefore, the computing speed is inferior to that of traditional programming languages. Shell script is a good tool for system management, but it is not enough to process a large number of numeric operations, because shell scripts is slow and uses a large amount of CPU resources, the allocation of Host resources is poor.

Writing and running the first script

Shell script is a text file

Note:

  1. The command is run from top to bottom, from left to right;
  2. Command issuing: multiple blank spaces between commands, options, and parameters are ignored;
  3. Blank lines will also be ignored, and the blank spaces opened by the [Tab] button will also be treated as blank keys;
  4. If you read an enter sign (CR), try to run the line (or string) command;
  5. If a row contains too many contents, you can use \ [enter] to extend it to the next row;
  6. "#" Can be used as an annotation! Any data added after # will be considered as annotated text and ignored!

The program written in the script will be run in one row. Now let's assume that the program file name you wrote is/home/dmtsai/shell. Sh, and how to run it:

  • Direct command issuing: The shell. Sh file must have the permission to read and run (RX), and then:
    • Absolute path: Use/home/dmtsai/shell. Sh to issue the command;
    • Relative Path: if the working directory is in/home/dmtsai/, run the./shell. Sh command.
    • Variable "path" function: Place shell. Sh in the directory specified by path, for example :~ /Bin/
  • Run in a bash program: Run Through "bash shell. Sh" or "sh shell. Sh ".

 

/Bin/sh is/bin/bash (link file), using sh shell. sh tells the system to run shell directly with the bash function. sh file, so shell. sh can be run as long as it has the r permission! You can also use the sh parameters such as-N and-X to check and track whether the shell. Sh syntax is correct.

  • Write the first script

 

[[email protected] ~]# mkdir scripts; cd scripts[[email protected] scripts]# vi sh01.sh#!/bin/bash# Program:#       This program shows "Hello World!" in your screen.# History:# 2005/08/23VBirdFirst releasePATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/binexport PATHecho -e "Hello World! \a \n"exit 0

 

  1. First line #! /Bin/Bash:
    Because Bash is used 『#! /Bin/bashTo declare the syntax in this file using the bash syntax! When this program is run, it can load the bash environment configuration file (generally non-Login Shell ~ /. Bashrc) and run Bash to run the following commands! (In many cases, if this line is not configured, the program may fail to run because the system may not be able to determine what shell the program needs to run !)

  2. Description of program content:
    In the entire script, except for the first line 『#! "Is used to declare the shell, and other # is used for" annotation! Therefore, the second line is used to describe the basic data of the entire program. In general, we recommend that you develop the Script: 1. content and functions; 2. version Information; 3. author and contact information; 4. file creation date; 5. history and so on. This will help rewrite and debug future programs!

  3. Announcement of major environment variables:
    We recommend that you configure some important environment variables. laruence believes that path and Lang (if used to output related information) are the most important! In this way, we can directly issue some external commands when this program is running, without having to write an absolute path!

  4. Main program section
    Write the main program! In this example, it is the line of Echo!

  5. Running result notification (define the return value)
    If a command runs successfully or not, you can use $? You can use the exit command to interrupt the program and return a value to the system. In our example, laruence uses exit 0, which means to exit the script and return a value of 0 to the system. Therefore, after running this script, if ECHO $? The value 0 is returned!

 

[[email protected] scripts]# sh sh01.shHello World !

In addition, you can also run this script using: "chmod A + x sh01.sh;./sh01.sh!

Create a good habit of writing shell scripts

 

  • Script functions;
  • Script version information;
  • The author and contact information of the script;
  • Copyright announcement method of script;
  • Script history (history );
  • Special commands in the script are issued using the "absolute path" method;
  • Environment variables required for script running are pre-declared and configured.

 

 

Chapter 2. Learn shell scripts

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.