Introduction to Shell programming

Posted by Salsaboy on Sat, 19 Feb 2022 13:43:00 +0100

Introduction to Shell programming

Symbols of references:

Single quotation mark: WYSIWYG

Double quotation marks: parse variables (treat the input as a whole)

Backquotes: parsing commands

No quotation marks: similar to double quotation marks

  • Why learn Shell programming

    Shell will be widely used in Linux system, and we also need to realize business automation in our work,
    For example: automatic backup, monitoring and automatic installation services.

    Shell programming is a programming language that Linux operation and maintenance personnel must know. The simplest programming language.
    Programming is also a necessary skill for operation and maintenance personnel:
    Shell and Python are the skills that operation and maintenance personnel must possess

  • What is Shell

    Shell is a command interpreter (translator). The commands and scripts of the command line will be interpreted through the shell, passed to the operating system, processed and output to the user

  • What is a Shell script

    Programs and commands are executed in files. This file and script are called Shell script files

  • Shell variable
    1. Global variable (environment variable)

      It takes effect in the whole system, usually in uppercase letters. There are some such variables in the system by default to meet the needs of the system and program.

      Example of system default environment variables:

      [root@centos ~]#echo $PS1
      [\[\e[34;1m\]\u@\[\e[0m\]\[\e[32;1m\]\H\[\e[0m\]\[\e[31;1m\] \w\[\e[0m\]]\$
      [root@centos ~]#echo $PATH 
      /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
      [root@centos ~]#echo $HOME
      /root
      [root@centos ~]#echo $SHELL
      /bin/bash
      [root@centos ~]#echo $PWD
      /root
      

      Custom environment variables:

      Method 1:

      [root@centos ~]#export JACK="I am Jack"
      [root@centos ~]#echo $JACK
      I am Jack
      

      Method 2:

      [root@centos ~]#ANDY="I am Andy"
      [root@centos ~]#echo $ANDY
      I am Andy
      [root@centos ~]#echo ${ANDY}   #You can use {} to distinguish multiple variables
      I am Andy
      

      CenOS environment variable priority profile

      /etc/profile
      ~/.bash_profile
      ~/.bashrc
      /etc/bashrc    #It is recommended to put the environment variable into / etc/bashrc in the future, with the highest priority
      
    2. Local variable (ordinary variable)

      Local variables are the most commonly used variables in Shell Scripting

      Representation:

      Variable name = value

      ​ a=1

      Naming rules:

      Letters, underscores, numbers, cannot start with numbers

      =		Assignment operator 
      value	 Variable content
      (Quotation marks, single quotation marks, and double quotation marks)
      

      Note: there must be no spaces on either side of the assignment symbol

  • expression
    1. [] bracket expression

      There must be spaces at both ends of the contents in brackets

      The string should be enclosed in double quotation marks

      [root@centos ~]#[ "a" = "b" ] && echo 1 || echo 0
      0
      [root@centos ~]#[ "a" = "a" ] && echo 1 || echo 0
      1
       If the expression holds, print 1, otherwise print 0
      
    2. Integer expression

      1) There must be spaces at both ends of the integer expression character
      2) There must be spaces at both ends of the brackets.
      3) The contents of variables and comparisons do not need quotation marks.

      >      -gt		greater than greater than
      >=     -ge		greater equal Greater equal to
      <      -lt		less than    less than
      <=     -le    less equal   Little equal to
      =      -eq     equal       be equal to
      ≠      -ne    not equal    Not equal to
      
      [root@centos ~]#a=1
      [root@centos ~]#[ $a -eq 2 ] && echo 1 || echo 0
      0
      [root@centos ~]#[ $a -eq 1 ] && echo 1 || echo 0
      1
       If the expression holds, print 1, otherwise print 0
      
    3. String expression

      -n When the variable content length [not] is 0, it is true(The expression is correct)not zero
      -z True when the variable content length is 0(The expression is correct)         zero
      a == a Are the strings the same```
      

      Note: double quotation marks shall be added to the string

      [root@centos ~]#jack="I am Jack"
      [root@centos ~]#echo $jack
      I am Jack
      [root@centos ~]#[ -z "$jack" ] && echo 1 || echo 0
      0
      [root@centos ~]#[ -n "$jack" ] && echo 1 || echo 0
      1
       by jack Assign a value, and then check whether the variable length is 0. If yes, print 0, otherwise print 1
      
  • Shell judgment sentence

    if judgment sentence grammar

    if [ expression ]
    then
       command
    fi
    
    [root@centos ~]#cat test.sh 
    #!/bin/bash
    a=10
    if [ $a -gt 1 ]
    then
        echo 1
    fi
    [root@centos ~]#bash test.sh 
    1
    #If the variable a is greater than 1, print 1
    

    If... Otherwise example:

    [root@centos ~]#cat test.sh 
    #!/bin/bash
    a=10
    if [ $a -gt 1 ]
    then
        echo 1
    else 
        echo 0
    fi
    [root@centos ~]#bash test.sh 
    1
    #If the variable a is greater than 1, print 1, otherwise print 0
    

    Fun try:

    [root@centos ~]#cat test.sh 
    #!/bin/bash
    boy="potential share"
    if [ "$boy" ==  "potential share" ]
    then
        echo "Talk to you first, friend"
    else
        echo "In vain"
    fi
    [root@centos ~]#bash test.sh 
    Talk to you first, friend
    
    [root@centos ~]#cat test.sh 
    if [ $(date +%w) -eq 6 ]
    then 
        echo "Let's travel together"
    else
        echo "Let's have a good class"
    fi
    [root@centos ~]#bash test.sh 
    Let's have a good class
    

    Realize multiple conditions

    Method 1:

    [root@centos ~]#cat test.sh 
    if [ $(date +%w) -eq 6 ] || [ $(date +%w) -eq 0 ]
    then 
        echo "Let's travel together"
    else
        echo "Let's have a good class"
    fi
    [root@centos ~]#bash test.sh 
    Let's have a good class
    

    Method 2:

    read Command to read user input interactively
    -p "Reminder:"
    -t "How long to wait for input"
    
    [root@centos ~/shsh]#cat test.sh 
    #!/bin/bash
    read -p "Please enter the instruction:" ps
    if [ "$ps" == "123" ]
    then
        echo "Correct instruction,Start the ship"
    elif [ "$ps" == "456" ]
    then
        echo "Special instruction,Go to earth"
    elif [ "$ps" == "789" ]
    then 
        echo "Super command, go home"
    else
        echo "Instruction error,Start self destruction"   
    fi
    [root@centos ~/shsh]#bash test.sh 
    Please enter the instruction: 123
     Correct instruction,Start the ship
    [root@centos ~/shsh]#bash test.sh 
    Please enter the instruction: 456
     Special instruction,Go to earth
    [root@centos ~/shsh]#bash test.sh 
    Please enter instruction: 789
     Super command, go home
    [root@centos ~/shsh]#bash test.sh 
    Please enter the instruction: 000
     Instruction error,Start self destruction
    
  • Exercise: Shell programming to compare the size of two integers

    Method 1:

    [root@centos ~]#bash daxiao.sh 
    Please enter two numbers: 11 22
    11<22
    [root@centos ~]#bash daxiao.sh 
    Please enter two numbers: 22 11
    22>11
    [root@centos ~]#bash daxiao.sh 
    Please enter two numbers: 11
    11=11
    [root@centos ~]#cat daxiao.sh 
    #!/bin/bash
    read -p "Please enter two numbers:" a b
    if [ $a -gt $b ] 
    then
        echo "$a>$b"
    elif [ $a -eq $b ] 
    then 
        echo "$a=$b"
    else 
        echo "$a<$b"
    fi
    

    Method 2:

    Special location variables:
    $1 The first parameter of the script file is assigned to $1
    $2 The second parameter of the script file is assigned to $2
    [root@centos ~]#cat b.sh
    echo $1 $2
    [root@centos ~]#bash b.sh b1 b2
    b1 b2				#b1 is the output of $1, and b2 is the output of $2
    #Assign b1 to $1 and b2 to $2 ()
    
    [root@centos ~]#cat daxiao.sh 
    #!/bin/bash
    a=$1
    b=$2
    if [ $a -gt $b ] 
    then
        echo "$a>$b"
    elif [ $a -eq $b ] 
    then 
        echo "$a=$b"
    else 
        echo "$a<$b"
    fi
    [root@centos ~]#bash daxiao.sh 11 22
    11<22
    [root@centos ~]#bash daxiao.sh 22 11
    22>11
    [root@centos ~]#bash daxiao.sh 22 22
    22=22
     After the script, enter the number directly and compare the values
    
  • for loop

    Syntax:

    for n in Value list
    do
        Execute command
    done
    

    Example:

    [root@centos ~]#cat for.sh 
    #!/bin/bash
    for n in 1 2 3 4 5
    do 
        echo "$n"
    done
    [root@centos ~]#bash for.sh 
    1
    2
    3
    4
    5
    [root@centos ~]#bash -x for.sh   # -x view execution process
    + for n in 1 2 3 4 5
    + echo 1
    1
    + for n in 1 2 3 4 5
    + echo 2
    2
    + for n in 1 2 3 4 5
    + echo 3
    3
    + for n in 1 2 3 4 5
    + echo 4
    4
    + for n in 1 2 3 4 5
    + echo 5
    5
    

    bash -x view execution

    Sequence for loop

    [root@centos ~]#cat for.sh 
    #!/bin/bash
    for n in {1..5}
    do 
        echo "$n"
    done
    [root@centos ~]#bash -x for.sh 
    + for n in '{1..5}'
    + echo 1
    1
    + for n in '{1..5}'
    + echo 2
    2
    + for n in '{1..5}'
    + echo 3
    3
    + for n in '{1..5}'
    + echo 4
    4
    + for n in '{1..5}'
    + echo 5
    5
    [root@centos ~]#bash for.sh 
    1
    2
    3
    4
    5
    

    Advanced: print 254 IP addresses 192.168.0.1-192.168.0.254

    [root@centos ~]#cat forip.sh 
    #!/bin/bash
    for n in {1..254}
    do 
        echo "192.168.0.$n"
    done
    
    [root@centos ~]#cat forip.sh 
    #!/bin/bash
    for n in 192.168.0.{1..254}
    do 
        echo $n
    done
    
  • Script writing habits:

    1. Take sh end.
    2. The first line at the beginning of the script #/ Who explains the contents of the bin/bash script.

    Since bash is the default under Linux, this line can also be omitted.

  • After class practice

    1. Compare integer sizes.

    2. Judge the date, travel every Saturday and Sunday, and have classes at other times

    3. Take out the Ip address of the current system and judge whether it is 192.168.0.111. If the prompt is correct, if not, give a prompt

    [root@centos ~/shsh]#cat ip.sh 
    #!/bin/bash
    ipadd=$(ifconfig eth0 | sed -nr 's#^.*inet (.*)net.*$#\1#gp') 
    
    if [ $ipadd == "192.168.0.111" ]
    then
        echo "system IP 192.168.0.111 Verification passed"
    else
        echo "system IP Verification failed, current IP Address: $ipadd"
    fi
    

    4. Print 192.168.0.100 – 192.168.0.120 IP addresses. When the IP address is the system IP address, give a prompt that an IP is the system IP

    #!/bin/bash
    for n in 192.168.0.{100..120}
    do
    	echo "$n"
    if [ $n == "192.168.0.111" ]
    then 
        echo "******$n Match successful, this IP For system IP address******"
    else
        echo "Match failed"
    fi
    done 
    

Topics: Linux Operation & Maintenance CentOS shell Ubuntu