Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Linux Shell Scripting     - How to Install Winusb in Ubuntu 14.04 (Linux)

- Linux startup and logon security settings (Linux)

- Oracle Client + PL SQL Developer enables remote access to the Oracle database (Database)

- Why learn and use C language (Programming)

- Browser caching mechanism on the analysis (Linux)

- Sublime Text 3 best features, plug-ins and settings (Linux)

- Using Ruby to build a simple HTTP service and sass environment (Server)

- MySQL database to open a remote connection method (Database)

- Shell for loop (Programming)

- Node.JS different ways to install under Ubuntu 15.04 (Linux)

- Linux Command Tutorial: cat command to view the contents of the file (Linux)

- The first IOS Objective-C program (Programming)

- Windows7 system using Vagrant to build Linux virtualized development environment (Linux)

- How to cool down your Ubuntu system (Linux)

- Linux platform host to prevent hacking skills (Linux)

- Manually create Oracle Database Explanations (Database)

- Linux Learning Notes: Users and Groups (Linux)

- To achieve a two-way static NAT stateless available modules on Linux (Linux)

- After the first remote installation GlassFish Web to remotely access their back office management system error solution appears (Server)

- Create a custom pixel format based on an existing image data BufferedImage (Programming)

 
         
  Linux Shell Scripting
     
  Add Date : 2017-04-13      
         
         
         
  1. What is the shell script
It is a scripting language, not a programming language.
You can use some logic, grammar circulation.
You can customize the subroutine, it is a collection of system commands.
shell script can be automated operation and maintenance, greatly increasing the efficiency of our work.

2, shell scripts configuration and execution method
Specifies bash path begins with the line:! # / Bin / bash
In the line beginning with # as an explanation
# NOTE own script content to facilitate their inspection; utf8 character set support for Chinese;
Names end in .sh script, which is used to distinguish a shell script
Execute scripts in two ways:
chmod a + x 1.sh add x execute permission;
./1.sh Can be executed directly, or write the absolute path /root/shell/1.sh
If you do not execute permissions can bash 1.sh or sh 1.sh
bash -x 1.sh can see during script execution
Lab Exercise:
1234 [root @ localhost shell] # cat 1.sh
#! / Bin / bash
# This is my first script
echo "hello world"

[Root @ localhost shell] # ls -l
-rw-r - r-- 1 root root 60. 6 Yue 16 19:28 1.sh
[Root @ localhost shell] # chmod a + x 1.sh
[Root @ localhost shell] # ls -l
-rwxr-xr-x 1 root root 60. 6 Yue 16 19:28 1.sh
[Root @ localhost shell] # ./1.sh
hello world
[Root @ localhost shell] # /root/shell/1.sh
hello world
[Root @ localhost shell] # / bin / sh 1.sh
hello world
[Root @ localhost shell] # bash -x 1.sh
+ Echo 'hello world'
hello world

Execution is the same as bash and sh, sh is bash soft connection file;
[Root @ localhost ~] # ls -l / bin / bash
-rwxr-xr-x. 1 root root 871700 10 Yue 16 2014 / bin / bash
[Root @ localhost ~] # ls -l / bin / sh
. Lrwxrwxrwx 1 root root 4 3 Yue 4 00:59 / bin / sh -> bash

3, learn to use the date command
date +% Y-% m-% d date +% y-% m-% d date
date +% Y-% m-% d = date +% F date
date +% H:% M:% S = date +% T Time
date +% s timestamp
date -d @ 1434248742 is calculated according to the current time timestamp
date -d "+ 1day" A day later date -d "-1day" the day before
date -d "-1month" a month ago
date -d "-1min" a minute ago
date +% w date +% W week


Lab Exercise:
[Root @ localhost shell] # date +% y
15
[Root @ localhost shell] # date +% Y
2015
[Root @ localhost shell] # date +% m
06
[Root @ localhost shell] # date +% d
16
[Root @ localhost shell] # date +% H
14
[Root @ localhost shell] # date +% M
01
[Root @ localhost shell] # date +% S
54

Counting from at 0:00 on January 1, 1970 to the present number of seconds;
[Root @ localhost shell] # date +% s
1434434874
[Root @ localhost shell] # date -d @ 1434434874
June 16, 2015 14:07:54 CST Tuesday

CST is China +8 hours
[Root @ yonglinux shell] # date -d @ 0
January 1, 1970 Thursday 08:00:00 CST

[Root @ localhost shell] # date +% F
2015-06-16
[Root @ localhost shell] # date +% T
14:04:17
[Root @ localhost shell] # date +% Y-% m-% d
2015-06-16
[Root @ localhost shell] # date + "% Y-% m-% d% H:% M:% S"
2015-06-16 14:05:13
[Root @ localhost shell] # date + "% F% T"
2015-06-16 14:05:38

on Tuesday

12 [root @ localhost shell] # date +% w
2

How much of the first year and 24 weeks

[Root @ localhost shell] # date +% W
twenty four

How many weeks of the year, 52 weeks;
[Root @ localhost shell] # echo "365/7" | bc
52

[Root @ localhost shell] # date -d "-1 day"
June 15, 2015 14:16:31 CST Monday
[Root @ localhost shell] # date -d "-1 day" + "% F% T"
2015-06-15 14:19:13
[Root @ localhost shell] # date -d "+1 day" + "% F% T"
2015-06-17 14:19:22
[Root @ localhost shell] # date -d "+1 month" + "% F% T"
2015-07-16 14:19:31
[Root @ localhost shell] # date -d "+1 year" + "% F% T"
2016-06-16 14:19:39
[Root @ localhost shell] # date -d "+1 week" + "% F% T"
2015-06-23 14:19:45
[Root @ localhost shell] # date -d "-10 hour" + "% F% T"
2015-06-16 04:19:59
[Root @ localhost shell] # date -d "-10 min" + "% F% T"
2015-06-16 14:10:15
[Root @ localhost shell] # date -d "-10 sec" + "% F% T"
2015-06-16 14:20:14

4, shell script variable
When a script is used more frequently and string variables should be used instead of string length is long.
When using conditional statements, often using variable if [$ a -gt 1]; then ...; fi
When referring to the results of a command, use variable substitution n = `wc -l 1.txt`
When writing the script and user interaction, the variable is also essential read -p "Input a number:" n; echo $ n
If you did not write this n, you can use $ REPLY
Built-in variables $ 0, $ 1, $ 2, $ # $ 0 for the script itself, $ 1 the first argument, the second argument $ 2, $ # represents the number of parameters;
Math a = 1; b = 2; c = $ (($ a + $ b)) or c = $ [$ a + $ b]

Lab Exercise:
The results refer to a command using variables instead
[Root @ localhost shell] # file = `which yum`
[Root @ localhost shell] # echo $ file
/ Usr / bin / yum
[Root @ localhost shell] # rpm -qf $ file
yum-3.2.29-60.el6.CentOS.noarch

Variables only take effect in the current shell, shell child will not take effect;
To sub-shell also take effect, use the export file to declare variables;
User interaction variables:
[Root @ localhost shell] # cat 2.sh
#! / Bin / bash
# Variables and user interaction
read -p "Please enter a number:" num
echo $ num
[Root @ localhost shell] # sh 2.sh
Please enter a number: 333
333

Parameter variables:
[Root @ localhost shell] # cat 3.sh
#! / Bin / bash
# About the parameters of the variable
echo "\ $ 1 = $ 1"
echo "\ $ 2 = $ 2"
echo "\ $ 3 = $ 3"
echo "\ $ # = $ #"
echo "\ $ 0 = $ 0"
[Root @ localhost shell] # sh 3.sh ABC linux world
$ 1 = ABC
$ 2 = linux
$ 3 = world
$ # = 3
$ 0 = 3.sh

Numeric variables:
12345678910 [root @ localhost shell] # a = 1; b = 2
[Root @ localhost shell] # c = $ a + $ b
[Root @ localhost shell] # echo $ c
1 + 2
[Root @ localhost shell] # c = $ [$ a + $ b]
[Root @ localhost shell] # echo $ c
3
[Root @ localhost shell] # c = $ (($ a + $ b))
[Root @ localhost shell] # echo $ c
3

5, shell logic judgment
Format 1: if the conditions; then statements; fi
Format 2: if conditions; then statement; else statements; fi
Format 3: if ...; then ...; elif ...; then ...; else ...; fi
Logic expression: if [$ a -gt $ b]; if [$ a -lt 5]; if [$ b -eq 10] and so on; attention everywhere spaces.
You can use the && and || or a combination of multiple conditions
Greater than> gt (greater than)
Less than < lt (less than)
Greater than or equal> = ge
Less than or equal < = le
Equal == eq (equal)
It is not equal to! = Ne
Lab Exercise:
[Root @ localhost shell] # cat if.sh
#! / Bin / bash
#if judgment statement, the condition is true, print true;
if:
then
    echo true
fi
[Root @ localhost shell] # sh if.sh
true

if the judge sentences 2;
[Root @ localhost shell] # cat if2.sh
#! / Bin / bash
#if judgment statement, the condition is true, returns true;
if [1 == 1]
then
echo "true"
fi
[Root @ localhost shell] # sh -x if2.sh
+ '[' 1 == 1 ']'
+ Echo true
true
[Root @ localhost shell] # sh if2.sh
true

if the judge sentences 3;

[Root @ localhost shell] # cat if3.sh
#! / Bin / bash
#if judgment statement, the condition is true Returns true, the condition is false, return false;
if [ "1" == "2"]
then
echo "true"
else
echo "false"
fi
[Root @ localhost shell] # sh if3.sh
false

Variables were compared
[Root @ localhost shell] # cat if4.sh
#! / Bin / bash
#if execution, variables were compared;
a = 1
if [ "$ a" == "2"]
then
echo "true"
else
echo "false"
fi
[Root @ localhost shell] # sh -x if4.sh
+ A = 1
+ '[' 1 == 2 ']'
+ Echo false
false

A plurality of judgment to add elif
[Root @ localhost shell] # cat if5.sh
#! / Bin / bash
#if judge sentences, the use of a plurality of judgment elif;
a = 1
if [ "$ a" == "2"]
then
echo "true"
elif [ "$ a" -lt 10]
then
echo "no false"
else
echo "false"
fi
[Root @ localhost shell] # sh if5.sh
no false

[$ A -lt 3] The same can be replaced (($ a < 3)); use brackets sure to note the space;
1234 [root @ localhost shell] # a = 1; if (($ a < 3)); then echo OK; fi
OK
[Root @ localhost shell] # a = 1; if [$ a -lt 3]; then echo OK; fi
OK

&& And successfully executed in front of the back after the execution;
|| Preceding execution or unsuccessful execution behind;
12345 [root @ localhost shell] # a = 5
[Root @ localhost shell] # if [$ a -lt 10] && [$ a -gt 2]; then echo OK; fi
OK
[Root @ localhost shell] # if [$ a -lt 10] || [$ a -gt 2]; then echo OK; fi
OK

Odd and even judges, digital inputs divided by 2, the remainder is 0 is even, non-zero is odd;
[Root @ yonglinux shell] # cat 4.sh
#! / Bin / bash
read -p "enter a number:" n
n1 = $ [$ n% 2]
if [$ n1 -eq 0]
then
echo "The number you enter is even"
else
echo "The number you entered is odd."
fi
[Root @ yonglinux shell] # sh 4.sh
enter a number: 23
The number you entered is odd
[Root @ yonglinux shell] # sh 4.sh
enter a number: 90
The number you enter is an even number

Determine whether the input is a number, not the number of exit; digital words determine odd or even;
`Echo $ n | grep -c '[^ 0-9]' character` match the number of lines is non-numeric input, and if a description is not digital.

[Root @ localhost shell] # cat 5.sh
#! / Bin / bash
# Determine whether the input is a direct exit numbers, not digital; digital word judgment is odd or even;
read -p "Please enter a number:" n
n2 = `echo $ n | grep -c '[^ 0-9]'`
if [$ n2 -eq 1]
then
echo "is not a pure number you enter, please re-enter."
exit 1
fi
n1 = $ [$ n% 2]
if [$ n1 -eq 0]
then
echo "The number you enter is even"
else
echo "The number you entered is odd."
fi
  
[Root @ localhost shell] # sh 5.sh
Please enter a number: abc
Not a pure number you enter, please re-enter
[Root @ localhost shell] # sh 5.sh
Please enter a number: 323
The number you entered is odd

6, if judged file, directory attributes
[-f File] determine whether it is a regular file, and there
[-d File] determine whether it is a directory, and there
[-e File] Analyzing the file or directory exists
If [-r file] Analyzing the file is readable
[-w File] determine whether a file can be written
If [-x file] judgment executable file
Lab Exercise:

1.sh exists behind the implementation
[Root @ localhost shell] # [-f 1.sh] && echo "1.sh exist"
1.sh exist

21.sh not exist behind the implementation.
12 [root @ localhost shell] # [-f 21.sh] || echo "1.sh not exist"
1.sh not exist

Determine whether a file exists
[Root @ localhost shell] # cat test.sh
#! / Bin / bash
# Judge 1.sh exists;
if [-e 1.sh]
then
echo "1.sh exist"
else
echo "1.sh not exist"
fi
[Root @ localhost shell] # sh test.sh
1.sh exist

exec usage, binding date variable experiment
exec command is used to invoke the command and execute the instructions. exec command is often used in shell script, you can call other commands. If you use the command in the current terminal, the terminal will exit immediately after completion of the specified command.
[Root @ localhost shell] # cat date.sh
#! / Bin / bash
#exec usage, binding date variable experiment;
d = `date +% F`
exec> /tmp/$d.log 2> & 1
echo "Begin at` date` "
ls / tmp / abc
cd / ddd
echo "End at` date` "

[Root @ localhost shell] # sh date.sh
[Root @ localhost shell] # cat /tmp/2015-06-16.log
Begin at 2015 Nian 06 Yue 16 16:49:54 CST Tuesday
ls: can not access / tmp / abc: No such file or directory
date.sh: line 7: cd: / ddd: No such file or directory
End at 2015 Nian 06 Yue 16 16:49:54 CST Tuesday

exec> /tmp/$d.log 2> & 1 represents execute the following line, right or wrong output information is written to the / tmp / directory date .log inside;

1, if judged some special usage
if [-z $ a] This means that when a variable is what happens when the value is empty
if [-e file!]; then indicates what will happen when the file does not exist
if (($ a < 1)); then ... the same as if [$ a -lt 1]; then ... [] can not use < ,>, ==, =,!> =, < = this symbol
$ 3 does not exist, and n is empty; determines whether the air;
[Root @ yong ~] # n = `wc -l / etc / passwd | awk '{print $ 3}'`
[Root @ yong ~] # echo $ n
  
[Root @ yong ~] # if [-z $ n]; then echo "\ $ n is null"; fi
$ N is null

if grep -q '123' 1.txt; then said that if 1.txt contains '123' row what happens?

1.txt contains 123; grep -q '123' 1.txt match OK, the return value is true;
[Root @ localhost shell] # cat 1.txt
123
sdwe
[Root @ localhost shell] # if grep -q "123" 1.txt; then echo kong; fi
kong

2, shell in the case judges
Format: case variable names in
                    value1)
                          command
                          ;;
                    value2)
                          command
                          ;;
                      *)
                        commond
                            ;;
                      esac
In case the program can be used in the condition |, representation or means, such as
2 | 3)
    command
    ;;
When the variable is 2 or 3, which is part of the command execution.

/etc/init.d/naginx inside case statements; the first argument matches the input whether the start stop reload restart conifgtest, enter other characters return

Usage: /etc/init.d/nginx {start | stop | reload | restart | configtest}
1234567891011121314151617181920 case "$ 1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  reload)
        reload
        ;;
  restart)
        restart
        ;;
  configtest)
        configtest
        ;;
  *)
        echo $ "Usage: $ 0 {start | stop | reload | restart | configtest}"
        RETVAL = 1
esac

For example, enter the letters prompted for a pure digital, digital input judgment is even or odd;
[Root @ localhost 0618] # cat case1.sh
#! / Bin / bash
# Asked to enter a number, odd or even judgment; not a number when prompted to enter the number, then exit;
read -p "please input a number:" n
n1 = `echo $ n | sed 's / [0-9] // g'`
# Sed is input to a digital replacement is empty, the return value is empty; enter the letter the return value is not empty;
if [! -z $ n1]
then
    echo "please input a number"
exit 1
fi
  
n2 = $ [$ n% 2]
case $ n2 in
  0)
    echo "even"
    ;;
  1)
    echo "odd"
    ;;
  *)
    echo "does not exist"
    ;;
esac

[Root @ localhost 0618] # sh -x case1.sh
+ Read -p 'please input a number:' n
please input a number:
de2
++ Echo de2
++ Sed 's / [0-9] // g'
+ N1 = de
+ '[' '!' -z De ']'
+ Echo 'please input a number'
please input a number
+ Exit 1
[Root @ localhost 0618] # sh case1.sh
please input a number: 234
Even
[Root @ localhost 0618] # sh case1.sh
please input a number: we
please input a number

case Experiment 2: Enter the blank is prompted to enter numbers and then quit; digital inputs 0-100 Analyzing performance; non-numeric input is prompted to enter a number and then exit;
Digital input will be negative and greater than 100 tips input is 0-100;
! # / Bin / bash # case experiment prompted to enter digital input is empty then exit; digital inputs 0-100 Analyzing performance; non-numeric prompts for digital input and then exit;
read -p "please input a number:" n
if [-z $ n]
then
    echo "Please input a number"
    exit 1
fi
n1 = `echo $ n | sed 's / [- 0-9] // g'`
Replace #sed added - for negative numbers;
if [! -z $ n1]
then
    echo "please input a number"
    exit 1
fi
  
if [$ n -ge 0] && [$ n -lt 60]
then
    tag = 1
elif [$ n -ge 60] && [$ n -lt 80]
then
    tag = 2
elif [$ n -ge 80] && [$ n -lt 90]
then
    tag = 3
elif [$ n -ge 90] && [$ n -le 100]
then
    tag = 4
else
    tag = 0
fi
  
case $ tag in
    1)
        echo "fail"
        ;;
    2)
        echo "fail"
        ;;
    3)
      echo "Good"
      ;;
    4)
      echo "excellent"
      ;;
    *)
      echo "digital inputs 0-100"
      ;;
esac

[Root @ localhost 0618] # sh case2.sh
please input a number: -200
Digital inputs 0-100
[Root @ localhost 0618] # sh case2.sh
please input a number: 101
Digital inputs 0-100

3, shell script loop
for loop syntax structure: for variable names in condition; do ... done
while loop syntax structure: while condition; do ... done with the cycle of death: that
break terminates the loop of the layer; continue to ignore continue under the code directly for the next cycle
exit exit shell


for loop experiments: List all directories under the / etc directory
[Root @ yong ~] # cat for.sh
#! / Bin / bash
for f in `ls / etc /`
do
if [-d / etc / $ f]
then
      ls -d "/ etc / $ f"
fi
done

while loop experiment: Analyzing the circulation load;

[Root @ yong ~] # cat load.sh
#! / Bin / bash
Script # Monitoring load, whichever w load load value within 1 minute of greater than 10, then 30 seconds send a message;
while:
do
load = `w | head -1 | awk -F" load average: " '{print $ 2}' | cut -d -f1`.
if [$ load -gt 10]
then
    top | mail -s "load is high: $ load" xxx@163.com
else
    exit 0
fi
    sleep 30
done

while loop experiment:

If the input is empty, a prompt to enter something, if you enter a character prompted for pure digital, pure digital printing digital input and exit;
1234567891011121314151617181920 [root @ localhost 0618] # cat while.sh
#! / Bin / bash
# Input is empty, you are prompted to enter what has been the end is not empty; if the input is prompted to enter only one letter is pure digital, pure digital input until the far end digital printing;
while:
do
    read -p "please input a number:" n
    if [-z $ n]
    then
        echo "Please enter a thing."
    continue
fi
    n1 = `echo $ n | sed 's / [- 0-9] // g'`
    if [! -z $ n1]
    then
        echo "Please enter a purely numeric"
    continue
fi
    break
done
echo $ n

continue to exit this cycle; the cycle continues, the cycle is not executed later;
break out of the entire loop, the loop will be back.
exit, then exit the entire script;


break experiment: the condition is a match to exit the entire loop;
[Root @ localhost 0618] # cat break.sh
#! / Bin / bash
#break experiment; match the criteria, then exit the entire loop; loop back will be executed;
for i in `seq 1 5`
do
    echo $ i
    if [$ i == 3]
then
        break
fi
echo $ i
done
echo OK

[Root @ localhost 0618] # sh break.sh
1
1
2
2
3
OK

continue the experiment; the condition is a match out of this loop, the loop continues;

1234567891011 #! / Bin / bash
for i in `seq 1 5`
do
    echo $ i
    if [$ i == 3]
    then
        continue
    fi
    echo $ i
done
echo OK

[Root @ localhost 0618] # sh continue.sh
1
1
2
2
3
4
4
5
5
OK

exit test; match the criteria, then exit the entire script;

#! / Bin / bash
for i in `seq 1 5`
do
    echo $ i
    if [$ i == 3]
    then
        exit 1
    fi
    echo $ i
done
echo OK

[Root @ localhost 0618] # sh break.sh
1
1
2
2
3

4, shell functions in
Function is to organize a piece of code into a small unit, and give this cell a name, when this code is used to directly call the name of this small unit can be.
Format: function f_name () {
                      command
            }
Function must be placed on top
Function where you can export a global variable;
Function Experiment 1: Define the input function, enter a character, then print a character;

#! / Bin / bash
input () {
    echo $ 1
    }
input yonglinux
[Root @ yong ~] # sh 1.sh
yonglinux

Function Experiment 2: Define sum function, summing operation;

12345678 #! / Bin / bash
sum () {
    s = $ [$ 1 + $ 2]
    echo $ s
}
sum 1 2
[Root @ localhost 0618] # sh 2.sh
3

Check function ip address;
#! / Bin / bash
# Check function ip address; enter a name card, output card corresponding ip address; $ 1 is the name of the NIC when entered interactively;
ip () {
    ifconfig | grep -A1 "$ 1" | tail -1 | awk '{print $ 2}' | awk -F ':' '{print $ 2}'
}
read -p "please input the eth name:" e
myip = `ip $ e`
echo "$ e address is $ myip"

[Root @ localhost 0618] # sh 2.sh
please input the eth name: eth0
eth0 address is 192.168.11.100
[Root @ localhost 0618] # sh 2.sh
please input the eth name: eth1
eth1 address is 192.168.20.100
[Root @ localhost 0618] # sh 2.sh
please input the eth name: lo
lo address is 127.0.0.1
     
         
         
         
  More:      
 
- iOS GCD multithreading simple to use (Programming)
- Linux host dual LAN transceiver package ARP problem (Linux)
- Security Configuration SQL Server 2000 database tutorial (Linux)
- Using nmcli commands to manage network in RedHat / CentOS 7.x (Linux)
- Replace font under Linux (Linux)
- C ++ precision performance test function (Programming)
- OpenVPN offsite interconnecting room availability and load balancing solution (Server)
- Spring AOP (Programming)
- Linux Mint brightness adjustment --xrandr command learning (Linux)
- OpenResty load balancing MySQL (Database)
- Linux user management (Linux)
- Ubuntu 14.04 Nvidia graphics driver installation and settings (Linux)
- Python decorators to learn and practice the actual usage scenarios (Programming)
- VirtualBox - Linux system virtual machine shared folders (Linux)
- Let CentOS perform PPPoE dial-up, ADSL can be used in a network environment! (Linux)
- OpenStack / Dev stack with neutron on Ubuntu 14.04 (Server)
- Install Java 8 on Ubuntu using PPA (Linux)
- Fundamentals of the Java virtual machine memory management principles (Programming)
- Oracle Database routine inspection (Database)
- Four IDS intrusion detection tool under Linux environment (Linux)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.