Wechat official number: [Cat twelve daily], welcome to leave a message and point out the problem, deep drift in the front of the tuanzi, cat twelve shovel shit officer, life not only code, but also cats and you.

Common commands

  • Echo for output

    Echo 'AymFX most Handsome'Copy the code
  • Variable used

    your_name="aymfx"
    echo $your_name
    echo ${your_name}
    Copy the code
  • A read-only variable

    Myname ="aymfx" echo $myname readonly myname myname=" #myname: readonly echo $mynameCopy the code
  • To delete a variable

    myname="aymfx"
    echo $myname
    unset myname
    echo $myname # no output
    Copy the code
  • Single quotes

    • Any character in a single quote is printed as is, and variables in a single quote string are invalid;
    • A single quotation mark cannot appear in a single quotation mark string (even with an escape character), but can appear in pairs as string concatenations.
  • Double quotation marks

    • You can have variables in double quotes
    • Escape characters can appear in double quotes
    myname="aymfx"
    str="hello \"$myname\""
    echo $str hello "aymfx"
    Copy the code
  • Get the length of the string

    String ="aymfx" echo ${#string} #Copy the code
  • Extract substring

    String ="aymfx" echo ${string:1Copy the code
  • Find substrings

    • Using the “expr” command in this case is only for Linux commands

      STRING="this is a string"
      SUBSTRING="hat"
      expr index "$STRING" "$SUBSTRING"     # 1 is the position of the first 't' in $STRING
      Copy the code
  • Shortest substring matching

    • ${string#substring}
    • ${string%substring}
    filename="bash.string.txt"
    
    echo ${filename#*.} #string.txt 
    echo ${filename%.*} #bash.string
    Copy the code
  • Shortest substring matching

    • ${string##substring}
    • ${string%%substring}
    filename="bash.string.txt"
    echo "After deletion of longest match from front:" ${filename##*.} # txt
    echo "After deletion of longest match from back:" ${filename%%.*}# bash
    Copy the code
  • Substring to replace

    • Replace the first occurrence of a substring with a substitution

      str='to be or not to be'
      echo ${str[@]/be/cat} #to cat or not to be
      Copy the code
      • Replace all occurrences of substrings

        str='to be or not to be'
        echo ${str[@]//be/cat} #to cat or not to cat
        Copy the code
      • Delete all occurrences of substrings (replace with empty strings)

        str='to be or not to be'
        echo ${str[@]// not/} #to be or not to be
        Copy the code
    • If you replace the occurrence of a substring at the beginning of $STR

      str='to be or not to be'
      echo ${str[@]/#to be/eat now} #eat now or not to be
      Copy the code
    • If it ends at $STR, it replaces the occurrence of the substring

      str="to be or not to be"
      echo ${str[@]/%be/eat}  # to be or not to eat
      Copy the code
  • An array of

    • Initialization (An array can hold multiple values with a single name. Array names are the same as variable names. Initialize arrays by allocating space-separated values contained in ().

      apple=1
      my_array=($apple banana "fruit basket" orange)
      echo ${#my_array[@]} # 4
      echo ${my_array[3]} #orange
      echo aymfx #aymfx
      echo ${my_array[0]} # 1
      Copy the code
    • Array members need not be contiguous or contiguous. Some members of the array can be left uninitialized.

    • The total number of elements in the array is referenced by ${# arrayName [@]}

  • Arithmetic operator

    • A plus b plus A plus B
    • A minus b minus a minus b.
    • A times b times a times b.
    • A/B division (integer)
    • Take the modulo of a%b (divided by the remainder of the integer b)
    • **a*** * * *bExponentiation (a equals a power of B)
  • Conditional statements

    # the first
    
    name='aymfx'
    if [ $name = 'aymfx' ];then
        echo "${name}Really handsome" # aymfx really handsome
    fi
    
    # the second
    
    name='aymfx'
    if [ $name = 'ly' ];then
        echo "${name}Really handsome" # aymfx really handsome
    else
        echo "There is no more${name}Never better." 
    fi
    
    # the third
    
    name='aymfx'
    if [ $name = 'ly' ]; then
        echo "${name}Really handsome" # aymfx really handsome
    elif [ $name = 'aymfx' ]; then
        echo "${name}Handsome burst" # aymFX is awesome
    else
        echo "There is no more${name}Never better." 
    fi
    
    # value comparison type
    comparison    Evaluated to true when
    $a -lt $b    $a < $b
    $a -gt $b    $a > $b
    $a -le $b    $a< =$b
    $a -ge $b    $a> =$b
    $a -eq $b    $a is equal to $b
    $a -ne $b    $a is not equal to $b
    
    Type of string comparison
    
    comparison    Evaluated to true when
    "$a" = "$b"     $a is the same as $b
    "$a"= ="$b"    $a is the same as $b
    "$a"! ="$b"    $a is different from $b
    -z "$a"         $a is empty
    
    
    # case
    
    mycase=1
    case $mycase in
        1) echo "You selected bash";;
        2) echo "You selected perl";;
        3) echo "You selected phyton";;
        4) echo "You selected c++";;
        5) exit
    esac
    Copy the code

    = must be surrounded by Spaces using “” around string variables to avoid shell extension of special characters to *

  • Loop structure

    
    # for loop
    
    # for
    for arg in [list]
    do
     command(s)...
    done
    
    #! /bin/bash
    names=(aymfx liya zhangmeng)
    for name in ${names[@]};do
        echo $name
    done
    
    # while
    while [ condition ]
    do
     command(s)...
    done
    
    COUNT=4
    while [ $COUNT -gt 0 ];do
        echo "value of count ${COUNT}"
        COUNT=$(($COUNT-1))
    done
    
    #bash until loop
    
    until [ condition ]
    do
     command(s)...
    done
    
    COUNT=1
    until [ $COUNT -gt 5 ];do
        echo "value of count ${COUNT}"
        COUNT=$(($COUNT+1))
    done
    
    NUMBERS=(951 402 984 651 360 69 408 319 601 485 980 507 725 547 544 615 83 165 141 501 263 617 865 575 219 390 237 412 566 826 248 866 950 626 949 687 217 815 67 104 58 512 24 892 894 767 553 81 379 843 831 445 742 717 958 609 842 451 688 753 854 685 93 857 440 380 126 721 328 753 470 743 527)
    for value in ${NUMBERS[@]};do
        if [ $value -eq 237 ]; then
            break;
        elif[$(($value % 2)) == 0 ]; then
            echo $value
        fi
    done
    
    # break and continue can be used to control the execution of loops for,while, and until constructs. Continue is used to skip the rest of a particular loop iteration, while break is used to skip the rest of the entire loop.
    
    Copy the code
  • The shell function

    • Function calls are equivalent to commands. You can pass parameters to a function by specifying parameters after the function name. The first argument in the function is called 1, the second argument is called 1, the second argument is called 1, the second argument is called 2, and so on
    function function_B {
      echo "Function B."
    }
    function function_A {
      echo "$1"
    }
    function adder {
      echo "$(($1 + $2))"
    }
    
    
    function_A "Function A."     # Function A.
    function_B                   # Function B.
    adder 12 56                  # 68
    Copy the code

Some explanation

  • #! Is a convention tag that tells the system what interpreter the script needs to execute, that is, which Shell to use.

    • #! /bin/bash
  • The method to run the script

    • Chmod +x./test.sh # enables the script to execute
    • /test.sh # Execute the script
    • /bin/sh test.sh
  • Variable types

    • Local variables Local variables are defined in a script or command and are only valid in the current shell instance. Programs started by other shells cannot access local variables.
    • Environment variables All programs, including those launched by the shell, have access to environment variables, and some programs need them to run properly. Shell scripts can also define environment variables if necessary.
    • Shell variables Shell variables are special variables set by the shell program. Some shell variables are environment variables and some are local variables, which ensure the normal operation of the shell
  • Value of the command output

    • You can do this by wrapping the command with ‘ ‘(called backquotes) or $()

      FILELIST=`ls`
      
      FileWithTimeStamp=/tmp/my-dir/file_$(/bin/date +%Y-%m-%d).txt
      Copy the code
  • Variable 1 refers to the first argument on the command line, variable 1 refers to the first argument on the command line, variable 1 refers to the first argument on the command line, variable 2 refers to the second argument, and so on. The variable $0 refers to the current script.

    Sh apple banner echo $0 #auto. Sh echo $1 #apple echo $# #2Copy the code
  • Special variables

    • $0– the current script file name |
    • $n– call the first N parameters passed to the script or calling function |
    • $#– the number of parameters passed to the script or function |
    • $@– | all passed to the script or function parameters
    • $*– | all passed to the script or function parameters
    • $?– the last execution of command exit status |
    • $$– ID of the current shell process. For a shell script, this is that they are performing the process ID. |
    • $!– the last process of background command |
    echo "Script Name: $0"
    function func {
        for var in $*
        do
            let i=i+1
            echo "The \$${i} argument is: ${var}"
        done
        echo "Total count of arguments: $#"
    }
    func We are argument
    
    #Script Name: auto.sh
    #The The $1 argument is: We
    #The $2 argument is: are
    #The $3 argument is: argument
    #Total count of arguments: 3
    
    function func {
        echo "--- \"\$*\""
        for ARG in "$*"
        do
            echo $ARG
        done
    
        echo "--- \"\$@\""
        for ARG in "$@"
        do
            echo $ARG
        done
    }
    func We are argument
    
    #--- "$*"
    #We are argument
    #--- "$@"
    #We
    #are
    #argument
    
    
    Copy the code
  • Common signal types

    • SIGINT: User sends interrupt signal (Ctrl + C)
    • SIGQUIT: User sends exit signal (Ctrl + C)
    • SIGFPE: An illegal math operation was attempted

    HUP INT QUIT ILL TRAP ABRT EMT FPE KILL BUS SEGV SYS PIPE ALRM TERM URG STOP TSTP CONT CHLD TTIN TTOU IO XCPU XFSZ VTALRM PROF WINCH INFO USR1 USR2

    trap "echo Booh!" SIGINT SIGTERM
    echo "it's going to run until you hit Ctrl+Z"
    echo "hit Ctrl+C to be blown away!"
    
    while true        
    do
        sleep 60       
    done
    
    trap booh 2 15
    
    trap "rm -f folder; exit" 2
    
    Copy the code
  • File tests (In general, you will need to do some file tests on a running file system. In this case, the shell will give you some useful commands to implement it.)

    • -<command> [filename]

    • [filename1] -<command> [filename2]

      # Use "-e" to test whether the file exists
      
      #! /bin/bash
      filename="package.json"
      if [ -e "$filename" ]; then
          echo "$filename exists as a file"
      fi
      
      # Use -d to test whether the directory exists
      directory_name="public"
      if [ -d "$directory_name" ]; then
          echo "$directory_name exists as a directory"
      fi
      
      Use "-r" to test whether the file has read permission for the user running the script/test
      filename='README.md'
      if [ ! -f "${filename}" ];then
          touch "${filename}"
      fi
      if [ -r "${filename}" ];then
          echoHave read permissionelse
          echoHave no legal powerfi
      Copy the code

If you think my article is ok, click a like or follow the next, there are wonderful stories waiting for you oh, but also can cloud masturbation cat