Shell basic notes 2-arithmetic and comparison operations

1. Let integer arithmetic 

  let variable name = variable 1 operator variable 2

  let++

  Note that the let command can only perform integer-related operations, and the operation results can only save integers ( division is rounded, and the rest has an error if there is a decimal )

2. Expr integer operation

  Arithmetic operations can only be integer operations ( division is rounded, the rest are reported with decimal errors ), and string operations can also be performed

  expr expression1 operator expression2

  The operator * must be preceded by '\' for escaping , and there must be a space between the operator and the two expressions (different from let)

  expr as an external command must be enclosed in backticks

    例:res=`expr $1 \* 4 +$3`

3. bc floating point arithmetic

  Pipeline application: variable = `echo" OPTION; OPERATIONS "| bc`, where scale is one of the most important options of bc, used to specify the number of decimal places output

    例:n=`echo "scale=3;13/2" | bc`

      echo $n

      Result: 6.500

4. String operation

  1. Length of output string

    Method 1: echo $ {# str1}: the length of the output variable $ str1

    Method 2: expr length $ str1: the length of the output variable $ str1

  2. The operation of taking substring

    Method 1: expr substr $ string $ position $ length  Note that the position number starts from 1

      str = 'abcde123 "

      expr substr $str 3 3

      Result: cde

    Method 2: echo $ {string: $ pos: $ length}  Note that the position number starts from 0

      str="abcde123"

      echo ${str:2:3}

      Result: cde

  3. String concatenation operation

    $str3="${str1}$str2"

    echo $ str3

  4. String replacement operation

    str="you and you and zhangsan"

    echo $ {str / you / YOU} # Replace only once

    结果:YOU and you and zhangsan

    echo $ {str // you / YOU} #Replace all

    YOU and YOU and zhangsan  

5. Integer comparison

  

6. String comparison

7. Logic operation

8. File testing

 

Guess you like

Origin www.cnblogs.com/guang2508/p/12709673.html