Linux Shell (1)

Shell overview

Shell is acommand line interpreter, which receives application/user commands and then calls the operating system kernel

Shell is also a very powerful programming language.Easy to write, easy to debug, and flexible

Insert image description here

Shell parser provided by Linux

[guozihan@hadoop100 ~]$ cat /etc/shells
/bin/sh
/bin/bash
/usr/bin/sh
/usr/bin/bash
/bin/tcsh
/bin/csh

The relationship between bash and sh

-rwxr-xr-x. 1 root root 964536 11月25 2021 bash
lrwxrwxrwx. 1 root root 10 8月25 20:20 bashbug -> bashbug-64
-rwxr-xr-x. 1 root root 6964 11月25 2021 bashbug-64
lrwxrwxrwx. 1 root root 4 8月25 20:20 sh -> bash

The default parser on Centos is bash

[guozihan@hadoop100 bin]$ echo $SHELL
/bin/bash

Getting Started with Shell Scripting

script format

The script starts with ==#!/bin/bash== (specifies the parser)

first script

Requirements: Create a Shell script to output helloworld

  • Practical examples

    First we create the folder program, then create the sh file in the folder and edit it with vim

    [guozihan@hadoop100 desktop]$ mkdir program

    [guozihan@hadoop100 desktop]$ cd program/

    [guozihan@hadoop100 program]$ touch helloword.sh

    [guozihan@hadoop100 program]$ vim helloword.sh

    #!/bin/bash
    echo "helloworld"
    

Commonly used execution methods of scripts

  • Use the relative path or absolute path of the bash or sh+ script (No need to give +x permission to script

    Relative path to sh+script

    [guozihan@hadoop100 program]$ sh ./helloworld.sh
    helloworld

    Absolute path to sh+script

    [guozihan@hadoop100 program]$ sh /home/guozihan/Desktop/program/helloworld.sh
    helloworld

    Relative path to bash+script

    [guozihan@hadoop100 program]$ bash ./helloworld.sh
    helloworld

    Relative path to bash+script

    [guozihan@hadoop100 program]$ bash /home/guozihan/桌面/program/helloworld.sh
    helloworld

  • Execute the script using the absolute path or relative path of the input script (Must have executable permission +x

    ①First, grant +x permission to the helloworld.sh script

    [guozihan@hadoop100 program]$ chmod +x helloworld.sh

    ②Execute script

    [guozihan@hadoop100 program]$ ./helloworld.sh
    helloworld

    [guozihan@hadoop100 program]$ /home/guozihan/桌面/program/helloworld.sh
    helloworld

Note: The first execution method essentially allows the bash parser to execute the script for you, so the script itself does not require execution permissions. The second execution method essentially means that the script needs to

Execute, so execution permission is required.

  • Add "." or source before the path of the script

    ①Existing file test.sh, the content is as follows

    #!/bin/bash

    A=5

    echo $A

    ②Use sh, bash, ./ and . to execute respectively. The results are as follows

    [guozihan@hadoop100 program]$ bash test.sh
    5

    [guozihan@hadoop100 program]$ sh test.sh
    5

    [guozihan@hadoop100 program]$ chmod +x test.sh

    [guozihan@hadoop100 program]$ ./test.sh
    5

    [guozihan@hadoop100 program]$ . test.sh
    5

reason:

The first two methods open a subshell in the current shell to execute the script content. When the script content ends, the subshell closes and returns to the parent shell.

The third method is to add "." or source before the script path, so that the script content can be executed in the current shell without opening a subshell.! This is why we need to source every time we modify the /etc/profile file.

The difference between opening a subshell and not opening a subshell is that the inheritance relationship of environment variables, such as the current variables set in the subshell, is not visible to the parent shell.

variable

System predefined variables

  • Commonly used system variables

    $HOME、$PWD、$SHELL、$USER 等

  • Case practice

    View the value of system variables

    [guozihan@hadoop100 ~]$ echo $HOME
    /home/guozihan

    Display all variables in the current shell: set

    [guozihan@hadoop100 ~]$ set

Custom variables

  • basic grammar

    (1) Define variables: variable name = variable value, note, =There must be no spaces before or after the number

    (2) Unset variable: unset variable name

    (3) Declare static variables: readonly variables, note:cannot unset

  • Variable definition rules

    (1)Variable names can consist of letters, numbers, and underscores, but cannot start with a number, it is recommended that environment variable names be in uppercase letters.

    (2)There cannot be spaces on either side of the equal sign

    (3)In bash, the default types of variables are all string types, and numerical operations cannot be performed directly.

    (4)If the value of the variable has spaces, it needs to be enclosed in double quotes or single quotes.

  • Case practice

    Define variable A

    [guozihan@hadoop100 ~]$ A=5

    [guozihan@hadoop100 ~]$ echo $A
    5

    Reassign a value to variable A

    [guozihan@hadoop100 ~]$ A=8

    [guozihan@hadoop100 ~]$ echo $A
    8

    Undo variable A

    [guozihan@hadoop100 ~]$ unset A

    [guozihan@hadoop100 ~]$ echo $A

    Declare static variable B=2 and cannot unset

    [guozihan@hadoop100 ~]$ readonly B=2

    [guozihan@hadoop100 ~]$ echo $B
    2

    [guozihan@hadoop100 ~]$ B=9
    -bash: B: read-only variable

    In bash, the default types of variables are all string types, and numerical operations cannot be performed directly.

    [guozihan@hadoop100 ~]$ C=1+2

    [guozihan@hadoop100 ~]$ echo $C
    1+2

    If the value of the variable has spaces, it needs to be enclosed in double quotes or single quotes.

    [guozihan@hadoop100 ~]$ D=I love sunchen
    bash: love: Command not found…

    [guozihan@hadoop100 ~]$ D=“I love sunchen”

    [guozihan@hadoop100 ~]$ echo $D
    I love sunchen

    Variables can be promoted to global environment variables and can be used by other Shell programs.

    export variables

    Add echo $B in helloworld.sh file

    #!/bin/bash 
    
    echo "helloworld" 
    echo $B
    

    [guozihan@hadoop100 program]$ ./helloworld.sh
    helloworld

    [guozihan@hadoop100 program]$ export B

    [guozihan@hadoop100 program]$ ./helloworld.sh
    helloworld
    2

special variables

$n

  • basic grammar

    $n Function description: n is a number, $0 represents the script name, $1-$9 represents the first to ninth parameters, and parameters above ten need to be enclosed in curly brackets, such as ${10})

  • Case practice

    [guozihan@hadoop100 program]$ touch parameter.sh

    [guozihan@hadoop100 program]$ vim parameter.sh

    #!/bin/bash
    echo '=$n='
    echo $0
    echo $1
    echo $
    

    [guozihan@hadoop100 program]$ chmod 777 parameter.sh

    [guozihan@hadoop100 program]$ ./parameter.sh cls xz
    =$n=
    ./parameter.sh
    cls
    xz

$#

  • basic grammar

    $# Function description: Get the number of all input parameters, often used in loops to determine whether the number of parameters is correct and to enhance the robustness of the script.

  • Practical examples

    [guozihan@hadoop100 program]$ vim parameter.sh

    #!/bin/bash
    echo '==========$n=========='
    echo $0
    echo $1
    echo $2
    echo '==========$#=========='
    echo $
    

    [guozihan@hadoop100 program]$ chmod 777 parameter.sh

    [guozihan@hadoop100 program]$ ./parameter.sh cls xz
    =$n=
    ./parameter.sh
    cls
    xz
    =$n=
    2

$*、$@

  • basic grammar

    $* Function description: This variable represents all parameters in the command line. $* treats all parameters as a whole.

    $@ Function description: This variable also represents all parameters in the command line, but $@ treats each parameter differently.

  • Case practice

    [guozihan@hadoop100 program]$ vim parameter.sh

    #!/bin/bash
    echo '==========$n=========='
    echo $0
    echo $1
    echo $2
    echo '==========$#=========='
    echo $#
    echo '==========$*=========='
    echo $*
    echo '==========$@=========='
    echo $@
    

    [guozihan@hadoop100 program]$ ./parameter.sh a b c d e f g
    =$n=
    ./parameter.sh
    a
    b
    =$n=
    7
    =$n=
    a b c d e f g
    =$n=
    a b c d e f g

$?

  • basic grammar

    $? Function description: Return status of the last executed command. If the value of this variable is 0, it proves that the previous command was executed correctly; if the value of this variable is non-0 (the specific number is determined by the command itself), it proves that the previous command was executed incorrectly.

  • Case practice

    Determine whether the helloworld.sh script is executed correctly

    [guozihan@hadoop100 program]$ ./helloworld.sh
    helloworld

    [guozihan@hadoop100 program]$ echo $?
    0

operator

  • basic grammar

    “$((operational expression))” or “$[operational expression]”

  • Case practice

    Calculate the value of (2+3)*4

    [guozihan@hadoop100 program]$ S=$[(2+3)*4]

    [guozihan@hadoop100 program]$ echo $S
    20

Conditional judgment

  • basic grammar

    (1)test condition

    (2) [condition] ( note that there should be spaces before and after condition )

    Note: If the condition is not empty, it means true, [guozihan] returns true, [] returns false

  • Common judgment conditions

    • Compare between two integers

      -eq equals (equal)

      -ne is not equal (not equal)

      -lt less than (less than)

      -le less than equal (less equal)

      -gt greater than (greater than)

      -ge greater equal

      Note: If it is a comparison between strings, use the equal sign "=" to judge equality; use "!=" to judge inequality.

    • Determine based on file permissions

      -r has read permission (read)

      -w has write permission (write)

      -x has execution permission (execute)

    • Judge by file type

      -e file exists

      -f The file exists and is a regular file

      -d The file exists and is a directory

  • Case practice

    Is 23 greater than or equal to 22?

    [guozihan@hadoop100 program]$ [ 23 -ge 22 ]

    [guozihan@hadoop100 program]$ echo $?
    0

    Does helloworld.sh have write permission?

    [guozihan@hadoop100 program]$ [ -w helloworld.sh ]

    [guozihan@hadoop100 program]$ echo $?

    0

    Does the file in the /home/atguigu/cls.txt directory exist?

    [guozihan@hadoop100 program]$ [ -e /home/guozihan/cls.txt ]

    [guozihan@hadoop100 program]$ echo $?
    1

    Multi-condition judgment( && means that the next command will be executed only when the previous command is executed successfully, || means that the next command will be executed only after the execution of the previous command failed )

    [guozihan@hadoop100 program]$ [ guozihan ] && echo OK || echo notOK
    OK

    [ guozihan@hadoop100 program ] $ [ ] && echo OK || echo notOK
    notOK

Process control(▲)

if judgment

  • basic grammar

    • single branch

      if [ 条件判断式 ];then
      	程序
      fi
      

      or

      if [ 条件判断式 ]
      then
      程序
      fi
      
    • multiple branches

      if [ 条件判断式 ]
      then
      	程序
      elif [ 条件判断式 ]
      then
      	程序
      else
      	程序
      fi
      

    Precautions:

    ①[Conditional judgment expression], there must be a space between the square brackets and the conditional judgment expression

    ②There must be a space after if

  • Case practice

    Enter a number. If it is 1, then banzhang zhen shuai is output. If it is 2, cls zhen mei is output. If it is other, nothing is output.

    [guozihan@hadoop100 program]$ touch if.sh
    [guozihan@hadoop100 program]$ vim if.sh
    
    #!/bin/bash
    if [ $1 -eq 1 ]
    then
    echo "banzhang zhen shuai"
    elif [ $1 -eq 2 ]
    then
    echo "cls zhen mei"
    fi
    
    [guozihan@hadoop100 program]$ chmod 777 if.sh
    [guozihan@hadoop100 program]$ ./if.sh 1
    banzhang zhen shuai
    [guozihan@hadoop100 program]$ ./if.sh 2
    cls zhen mei
    

case statement

  • basic grammar

    case $variable name in

    "value 1")

    ​ If the value of the variable is equal to value 1, then execute program 1

    ;;

    "value 2")

    ​ If the value of the variable is equal to value 2, then execute program 2

    ;;

    ​ …Omit other branches…

    *)

    ​ If the value of the variable is not the above value, execute this program

    ;;

    esac

    Precautions:

    (1) The end of the case line must be the word "in", and each pattern match must end with a right bracket ")".

    (2) The double semicolon ";;" indicates the end of the command sequence, which is equivalent to break in Java.

    (3) The last "*)" indicates the default mode, which is equivalent to java

  • Case practice

    Enter a number, if it is 1, output banzhang, if it is 2, output cls, if it is other, output renyao.

    [guozihan@hadoop100 program]$ touch case.sh
    [guozihan@hadoop100 program]$ vim case.sh
    
    #!/bin/bash
    case $1 in
    "1")
    echo "banzhang"
    ;;
    "2")
    echo "cls"
    ;;
    *)
    echo "renyao"
    ;;
    esac
    
    [guozihan@hadoop100 program]$ chmod 777 case.sh 
    [guozihan@hadoop100 program]$ ./case.sh 
    renyao
    [guozihan@hadoop100 program]$ ./case.sh 1
    banzhang
    
    

for loop

  • Basic grammar 1

    for (( 初始值;循环控制条件;变量变化 ))
    do
    	程序
    done
    
  • Case practice 1

    Add from 1 to 100

    [guozihan@hadoop100 program]$ touch for1.sh
    [guozihan@hadoop100 program]$ vim for1.sh 
    
    #!/bin/bash
    sum=0
    for((i=0;i<=100;i++))
    do
    sum=$[$sum+$i]
    done
    echo $sum
    
    [guozihan@hadoop100 program]$ chmod 777 for1.sh 
    [guozihan@hadoop100 program]$ ./for1.sh 
    5050
    
  • Basic Grammar 2

    for 变量 in123do
    程序
    done
    
  • Case practice 2

    Print all input parameters

    [guozihan@hadoop100 program]$ touch for2.sh
    [guozihan@hadoop100 program]$ vim for2.sh 
    
    #!/bin/bash
    #打印数字
    for i in cls mly wls
    do
    echo "ban zhang love $i"
    done
    
    [guozihan@hadoop100 program]$ chmod 777 for2.sh 
    [guozihan@hadoop100 program]$ ./for2.sh 
    ban zhang love cls
    ban zhang love mly
    ban zhang love wls
    
  • The difference between $* and $@

    Both $* and $@ represent all parameters passed to a function or script, when not enclosed by double quotes "", all parameters will be output in the form of $1 $2...$n.

    When they are enclosed in double quotes "", $* will output all parameters as a whole in the form of "$1 $2...$n"; $@ will separate each parameter in the form of "$1" "$2" ...output all parameters in the form of "$n"

while loop

  • basic grammar

    while [ 条件判断式 ]
    do
    程序
    done
    
  • Case practice

    Add from 1 to 100

    [guozihan@hadoop100 program]$ touch while.sh
    [guozihan@hadoop100 program]$ vim while.sh 
    
    #!/bin/bash
    sum=0
    i=1
    while [ $i -le 100 ]
    do
    sum=$[$sum+$i]
    i=$[$i+1]
    done
    echo $sum
    
    [guozihan@hadoop100 program]$ chmod 777 while.sh 
    [guozihan@hadoop100 program]$ ./while.sh 
    5050
    

read reads console input

  • basic grammar

    read (option) (parameter)

    ①Option:

    -p: Specifies the prompt when reading the value;

    -t: Specify the waiting time (seconds) when reading the value. If -t is not added, it means waiting forever.

    ②Parameters

    Variable: Specify the variable name to read the value

  • Case practice

    Within 7 seconds, read the name entered by the console.

    [guozihan@hadoop100 program]$ touch read.sh
    [guozihan@hadoop100 program]$ vim read.sh 
    
    #!/bin/bash
    read -t 7 -p "Enter your name in 7 seconds :" NN
    echo $NN
    
    [guozihan@hadoop100 program]$ chmod 777 read.sh 
    [guozihan@hadoop100 program]$ ./read.sh 
    Enter your name in 7 senconds:guozihan
    guozihan
    

Guess you like

Origin blog.csdn.net/pipihan21/article/details/132580049