Write a simple shell script

Source: Internet
Author: User
Tags ming mysql client mysql backup

In some complex Linux maintenance work, a lot of repetitive input and operation is not only time-consuming and error-prone, but writing a proper shell script, can be batch processing, automating a series of maintenance tasks, greatly reducing the burden on administrators


Shell Script Basics

1. Writing the first shell script

A shell script in Linux is a special application, between the operating system kernel and the user, acting as a command interpreter, responsible for receiving the user's instructions and interpreting them, passing the required actions to the kernel execution, and outputting the execution results

Common Shell Interpreter

You can learn about the shell types supported by the current system through the/etc/shells file. And/bin/bash is the default shell script for most Linux

[Email protected] ~]# cat/etc/shells/bin/sh/bin/bash/sbin/nologin ...//omit part of the content


Writing a script file

Save the various Linux commands you normally use in order to a text file, and then add execute permissions, which is a shell script.

[[email protected] ~]# vim first.sh            //New first.sh file #!/bin/bash                                 //Script Declaration                 #  This is my first Shell-Script.           //Annotation Information cd /boot                                    //Executable Statement pwdls -lh vml*[[email protected] ~]# . first.sh               //the following four ways to execute scripts [[email protected]  ~]# sh  first.sh[[email protected] ~]# source first.sh[[email protected] ~]# chmod  +x first.sh[[email protected] ~]# ./first.sh               //this way requires the file has X permission, and the above three kinds do not need


2. Redirection and pipeline operation

(1) REDIRECT Operation

Linux systems use files to describe a variety of hardware, devices and other resources. While the user processes information through the operating system, including the following types of interactive device files:


In the actual Linux system maintenance, can change the output, the input content direction, does not use the default standard input, the output device, this kind of operation is called the redirect


(2) Pipe operation

Pipeline operations provide a mechanism for collaborative work between different commands, located in the pipe symbol "|" The result of the command output on the left, as the processing object for the right command, can have multiple pipelines in the same command

[[email protected] ~]# grep "bash$"/etc/passwdroot:x:0:0:root:/root:/bin/bashteacher:x:500:500:benet Linux teacher:/ Home/teacher:/bin/bash[[email protected] ~]# grep "bash$"/etc/passwd | Awk-f: ' {print $1,$7} ' Root/bin/bashteacher/bin/bash



Using shell variables

Shell variables are used to store the specific parameters that the system and the user need to use, and these parameters can vary according to the user's settings or changes in the system environment. With shell variables, the shell program provides more flexible functionality and is more adaptable

The types of common shell variables include custom variables, environment variables, positional variables, pre-defined variables

Custom variables: defined, modified, and used by the user

Environment variables: maintained by the system for setting up the working environment

Positional variables: Passing parameters to the script through the command line

Predefined variables: A class of variables built into bash that cannot be modified directly


1. Custom variables

(1) Define a new variable

The basic format for defining variables is "variable name = variable Value", the variable name begins with a letter or underscore, is case-sensitive, and is recommended for all uppercase

(2) Viewing and referencing the value of a variable

The basic format is: Echo $ variable Name

[[email protected] ~]# xing=yang[[email protected] ~]# ming=shufan[[email protected] ~]# echo $xingyang [[email protected] ~]# echo $xing $mingyang shufan[[email protected] ~]# echo ${xing}shufanyangshufan


(3) Special operation for assigning values to variables

Use quotation marks when assigning values:

Double quotation marks ("): When you include spaces in an assignment, you must use double quotation marks, allowing you to refer to other variable values through the $ symbol

Single quotation mark ('): Single quotation marks must be used when special characters are included in assignment content

Anti-apostrophe ('): command substitution, extracting output from command execution

[Email protected] ~]# xingming= "Yang $ming"//double quotation mark application [[email protected] ~]# echo $xingmingyang shufan[[email Protect Ed] ~]# xingming= ' yang $ming '//single quote application [[email protected] ~]# echo $xingmingyang $ming [[email protected] ~]# aaa= ' GRE P "bash$"/etc/passwd '//anti-apostrophe application [[email protected] ~]# echo $aaaroot: X:0:0:root:/root:/bin/bash

In addition to the above, you can also use the Read command to assign values

[email protected] ~]# read Xingyang[[email protected] ~]# echo $xingyang


(4) Setting the scope of the variable

    By default, the newly defined variable is only valid in the current shell environment, called a local variable, and cannot be used when entering a subroutine or a new child shell environment. In order for user-defined variables to continue to be used in multiple child shell environments, you can export the specified variable as a global variable through the internal command export, specifying multiple variable names as parameters, and separating the variable names with commas

[[email protected] ~]# echo  $xing   $mingyang  shufan[[email protected] ~ ]# export xing ming           //will Xing, Ming set as global variable [[email protected] ~]# bash                        //into sub-shell environment [[email  protected] ~]# echo  $xing   $ming             //calls the parent shell's global variable yang shufan  [[email protected] ~]# exit                         //return to the original shell environment [[email protected] ~]# export  xingming=yangshufan[[ email protected] ~]# echo  $xingming             //Create a new name for XingminGlobal variable Yangshufan of G 


(5) Operation of numerical variables

In a bash shell environment, you can only perform simple integer operations, do not support decimal operations, and use the expr command, in the following format:

Expr variable 1 operator variable 2 [operator variable 3] ...

Some of the commonly used operators are as follows:

Addition Operation: +

Subtraction Operations:-

Multiplication: \* cannot use * only, otherwise it will be treated as a file wildcard

Division Operation:/

Modulo (take out) operation:% calculates the remainder after dividing the value

[[email protected] ~]# x=35[[email protected] ~]# y=16[[email protected] ~]# expr $x + $y//plus 51[[email protected] ~]# E xpr $x-$y//minus 19[[email protected] ~]# expr $x \* $y//multiply 560[[email protected] ~]# expr $x/$y//except 2[[email prot  Ected] ~]# expr $x% $y//take 3[[email protected] ~]# abc= ' expr $x + $y '//Assign the result of the operation to the variable Abc[[email protected] ~]# Echo $ABC 51



2. Environment variables

Environment variables are created by the system in advance of a class of variables, the main user set up the user's working environment, automatically maintained by the Linux system, will change with the user state changes, you can use the env command to view the current working environment environment variables


The path variable is used for the executable program's default search path

[Email protected] ~]# echo $PATH/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/ Bin:/root/bin[[email protected] ~]# path= "$PATH:/root" [[email protected] ~]# echo $PATH/usr/lib64/qt-3.3/bin:/usr/ Local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:/root


3. Position variables

Positional variables are also called positional parameters, using $, $, $ 、...、 $9

[[email protected] ~]# vim xxx.sh#!/bin/bashsum= ' expr $ + $ ' echo ' $ + $ = $sum ' [[email protected] ~]#. Xxx.sh 3412 + 46[[email protected] ~]#. xxx.sh 10 5010 + 50 = 60



4. Pre-defined variables

Predefined variables are a special class of variables that are predefined by bash programs, and users can only use predefined variables, not create new predefined variables, or assign values to predefined variables. Using the $ symbol and another symbol combination, here are a few of the commonly used pre-defined variables:

$#: Indicates the number of positional parameters in the command line

$*: Represents the contents of all positional parameters

$?: Represents the return state after the previous command was executed, with a return value of 0 indicating correct execution, and not 0 for exception execution

$ A: Represents the name of the currently executing script or program


[email protected] ~]# cat mybak.sh#!/bin/bashtarfile=beifen-' Date +%s '. Tgztar zcf $TARFILE $* &>/dev/nullecho "has  Execute a $ script, "echo" to complete the backup of $# objects "echo" specific content includes: $* "[[email protected] ~]#./mybak.sh/etc/passwd/etc/shadow has been executed./mybak.sh Script, complete backup of 2 objects specific content includes:/etc/passwd/etc/shadow




Shell scripts and task scheduling

Case: a company using MySQL database, need to the MySQL server in the Yang library for remote backup, daily 2:30, each backup as a separate. sql file, and then compressed into the. tar.gz format, the file name embedded in the date and time when the backup was performed


The configuration steps are as follows:

(1) Create a dedicated database backup account YSF, which allows you to connect to the MySQL database from the backup host 192.168.1.2 and grant read access to the Yang library. When using the Backup tool mysqldump, you also need to set select and lock tables permissions on the library


(2) Test database access from the MySQL client, query authorization is valid, or test using the backup Mysqldump tool



(3) Write MySQL backup script on MySQL client and test to be able to backup successfully


(4) Set up scheduled Tasks




Write a simple shell script

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.