Linux基础入门 --13 DAY(SHELL脚本编程基础)

算数运算 

        1.shell支持算数运算,但只支持整数,不支持浮点数

        2.bash中的算数运算符

+

-

*

/

%        取模

**        乘方

        let命令 

[root@localhost ~]# type let
let is a shell builtin
[root@localhost ~]# help let
let: let arg [arg ...]
    Evaluate arithmetic expressions.
    
    Evaluate each ARG as an arithmetic expression.  Evaluation is done in
    fixed-width integers with no check for overflow, though division by 0
    is trapped and flagged as an error.  The following list of operators is
    grouped into levels of equal-precedence operators.  The levels are listed
    in order of decreasing precedence.
    
        id++, id--    variable post-increment, post-decrement
        ++id, --id    variable pre-increment, pre-decrement
        -, +        unary minus, plus
        !, ~        logical and bitwise negation
        **        exponentiation
        *, /, %        multiplication, division, remainder
        +, -        addition, subtraction
        <<, >>        left and right bitwise shifts
        <=, >=, <, >    comparison
        ==, !=        equality, inequality
        &        bitwise AND
        ^        bitwise XOR
        |        bitwise OR
        &&        logical AND
        ||        logical OR
        expr ? expr : expr
                conditional operator
        =, *=, /=, %=,
        +=, -=, <<=, >>=,
        &=, ^=, |=    assignment
    
    Shell variables are allowed as operands.  The name of the variable
    is replaced by its value (coerced to a fixed-width integer) within
    an expression.  The variable need not have its integer attribute
    turned on to be used in an expression.
    
    Operators are evaluated in order of precedence.  Sub-expressions in
    parentheses are evaluated first and may override the precedence
    rules above.
    
    Exit Status:
    If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise

        示例:

[root@localhost ~]# i=10; let j=i++; echo j=$j i-$i
j=10 i-11
[root@localhost ~]# i=10; let j=++i; echo j=$j i-$i
j=11 i-11

        $[ ]

[root@localhost ~]# echo $[RANDOM%7]
0
[root@localhost ~]# echo $[RANDOM%7]
2
[root@localhost ~]# echo $[RANDOM%7]
4
[root@localhost ~]# echo -e "\e[1;$[RANDOM%7+31]mLOVER\e[0m"
LOVER
[root@localhost ~]# echo -e "\e[1;$[RANDOM%7+31]mLOVER\e[0m"
LOVER
[root@localhost ~]# echo -e "\e[1;$[RANDOM%7+31]mLOVER\e[0m"
LOVER

        expr 

[root@localhost ~]# expr 5 / 2
2
[root@localhost ~]# expr 2 + 3
5

[root@localhost ~]# expr 2 * 3
expr: syntax error
[root@localhost ~]# expr 2 \* 3
6
[root@localhost ~]# expr 2 '*' 3
6
[root@localhost ~]# expr 2 "*"  3
6

        BC 

[root@localhost ~]# bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 


scale=3

2/3
.666
^C
(interrupt) Exiting bc.
[root@localhost ~]# echo 1+1 | bc
2

        declare -i  

[root@localhost ~]# declare -i sum=1+1
[root@localhost ~]# echo $sum
2

        $(( )) 

[root@localhost ~]# echo $((1+1))
2

        范例:鸡兔同笼脚本

#!/bin/bash

HEAD=35
FOOT=94

RABBIT=$[(FOOT-HEAD-HEAD)/2]
CHOOK=$[HEDA-RABBIT]

echo RABBIT:$RABBIT
echo CHOOK: $CHOOK

[root@localhost ~]# . chook_rabbit.sh 
RABBIT:12
CHOOK: 23

        范例:面试题,求出所有人的年龄

[root@localhost ~]# vim age

wtj=16
zyf=17
wzh=18

[root@localhost ~]# cat age | grep -Eo "[0-9]+"| tr "\n" "+"| grep -Eo ".*[0-9]+"
16+17+18
[root@localhost ~]# cat age | grep -Eo "[0-9]+"| tr "\n" "+"| grep -Eo ".*[0-9]+" | bc
51 

逻辑运算 

        true,false

        与:&

        1 & 1 =1

        1 & 0 = 0

        0 & 1 = 0

        0 & 0 = 0

        或:|

        1 | 1 =1

        1 | 0 =1

        0 | 1 = 1

        0 | 0 = 0

非:!

        !1 = 0

        !0 = 1

异或:^

        异或两个值相同为假,不同为真

        1 ^ 1 = 0

        1 ^ 0 = 1

        0 ^ 1 = 1

        0 ^ 0 = 0

        范例:

[root@localhost ~]# true 
[root@localhost ~]# echo $?
0
[root@localhost ~]# false
[root@localhost ~]# echo $?
1

[root@localhost ~]# i=4
[root@localhost ~]# j=12
[root@localhost ~]# let a=j^i
[root@localhost ~]# echo $a
8

[root@localhost ~]# i=10;j=20;i=$[i^j];j=$[j^i];i=$[i^j];echo i=$i j=$j
i=20 j=10

短路运算 

        1.短路与

        cmd1 && cmd2

        第一个命令为真则执行第二个命令,最终结果由第二个命令判断

        第一个命令为假,则不需要执行第二个命令,最终结果为假

        2.短路或

        第一个命令为真,则不需要执行第二个命令,最终结果为真

        第一个命令为假,则执行第二个命令,最终结果由第二个命令判断 

条件测试命令 

        条件测试命令:

        1. test EXPRESSION

        2. [ EXPRESSION ]

        3. [[ EXPRESSION ]] 

        注意:EXPRESSION前后必须有空白字符

        范例:
[root@localhost ~]# type [
[ is a shell builtin
[root@localhost ~]# help [
[: [ arg... ]
    Evaluate conditional expression.
    
    This is a synonym for the "test" builtin, but the last argument must
    be a literal `]', to match the opening `['.
[[ ... ]]: [[ expression ]]
    Execute conditional command.
    
    Returns a status of 0 or 1 depending on the evaluation of the conditional
    expression EXPRESSION.  Expressions are composed of the same primaries used
    by the `test' builtin, and may be combined using the following operators:
    
      ( EXPRESSION )    Returns the value of EXPRESSION
      ! EXPRESSION        True if EXPRESSION is false; else false
      EXPR1 && EXPR2    True if both EXPR1 and EXPR2 are true; else false
      EXPR1 || EXPR2    True if either EXPR1 or EXPR2 is true; else false
    
    When the `==' and `!=' operators are used, the string to the right of
    the operator is used as a pattern and pattern matching is performed.
    When the `=~' operator is used, the string to the right of the operator
    is matched as a regular expression.
    
    The && and || operators do not evaluate EXPR2 if EXPR1 is sufficient to
    determine the expression's value.
    
    Exit Status:
    0 or 1 depending on value of EXPRESSION.
[root@localhost ~]# help test
test: test [expr]
    Evaluate conditional expression.
    
    Exits with a status of 0 (true) or 1 (false) depending on
    the evaluation of EXPR.  Expressions may be unary or binary.  Unary
    expressions are often used to examine the status of a file.  There
    are string operators and numeric comparison operators as well.
    
    The behavior of test depends on the number of arguments.  Read the
    bash manual page for the complete specification.
    
    File operators:
    
      -a FILE        True if file exists.
      -b FILE        True if file is block special.
      -c FILE        True if file is character special.
      -d FILE        True if file is a directory.
      -e FILE        True if file exists.
      -f FILE        True if file exists and is a regular file.
      -g FILE        True if file is set-group-id.
      -h FILE        True if file is a symbolic link.
      -L FILE        True if file is a symbolic link.
      -k FILE        True if file has its `sticky' bit set.
      -p FILE        True if file is a named pipe.
      -r FILE        True if file is readable by you.
      -s FILE        True if file exists and is not empty.
      -S FILE        True if file is a socket.
      -t FD          True if FD is opened on a terminal.
      -u FILE        True if the file is set-user-id.
      -w FILE        True if the file is writable by you.
      -x FILE        True if the file is executable by you.
      -O FILE        True if the file is effectively owned by you.
      -G FILE        True if the file is effectively owned by your group.
      -N FILE        True if the file has been modified since it was last read.
    
      FILE1 -nt FILE2  True if file1 is newer than file2 (according to
                       modification date).
    
      FILE1 -ot FILE2  True if file1 is older than file2.
    
      FILE1 -ef FILE2  True if file1 is a hard link to file2.
    
    String operators:
    
      -z STRING      True if string is empty.
    
      -n STRING
         STRING      True if string is not empty.
    
      STRING1 = STRING2
                     True if the strings are equal.
      STRING1 != STRING2
                     True if the strings are not equal.
      STRING1 < STRING2
                     True if STRING1 sorts before STRING2 lexicographically.
      STRING1 > STRING2
                     True if STRING1 sorts after STRING2 lexicographically.
    
    Other operators:
    
      -o OPTION      True if the shell option OPTION is enabled.
      -v VAR     True if the shell variable VAR is set
      ! EXPR         True if expr is false.
      EXPR1 -a EXPR2 True if both expr1 AND expr2 are true.
      EXPR1 -o EXPR2 True if either expr1 OR expr2 is true.
    
      arg1 OP arg2   Arithmetic tests.  OP is one of -eq, -ne,
                     -lt, -le, -gt, or -ge.
    
    Arithmetic binary operators return true if ARG1 is equal, not-equal,
    less-than, less-than-or-equal, greater-than, or greater-than-or-equal
    than ARG2.
    
    Exit Status:
    Returns success if EXPR evaluates to true; fails if EXPR evaluates to
    false or an invalid argument is given. 

变量测试 

        -v VAR 变量VAR是否设置

        示例:判断NAME变量是否设置

[ -v NAME ]

        范例:

[root@localhost ~]# [ -v NAME ]
[root@localhost ~]# echo $?
1
[root@localhost ~]# NAME=wtj
[root@localhost ~]# echo $?

[root@localhost ~]# unset NAME
[root@localhost ~]# test -v NAME
[root@localhost ~]# echo $?
1

数值测试

arg1 OP arg2   Arithmetic tests.  OP is one of -eq, -ne,
                     -lt, -le, -gt, or -ge.

-eq =

-ne !=

-lt <

-le <=

-gt >

-ge >=

        示例:

[root@localhost ~]# i=16
[root@localhost ~]# j=18
[root@localhost ~]# [ $i -lt $j ]
[root@localhost ~]# echo $?
0
[root@localhost ~]# test  $i -lt $j 
[root@localhost ~]# echo $?

字符串测试 

test || [ ]

String operators:
    
      -z STRING      True if string is empty.
    
      -n STRING
         STRING      True if string is not empty.
    
      STRING1 = STRING2
                     True if the strings are equal.
      STRING1 != STRING2
                     True if the strings are not equal.
      STRING1 < STRING2
                     True if STRING1 sorts before STRING2 lexicographically.
      STRING1 > STRING2
                     True if STRING1 sorts after STRING2 lexicographically.

[[ ]]

When the `==' and `!=' operators are used, the string to the right of
    the operator is used as a pattern and pattern matching is performed.
    When the `=~' operator is used, the string to the right of the operator
    is matched as a regular expression.
 

        范例:

[root@localhost ~]# title=wtj
[root@localhost ~]# [ -z $title ]
[root@localhost ~]# echo $?
1

[root@localhost ~]# [ -n $title ]
[root@localhost ~]# echo $?
0

文件测试 

    File operators:
    
      -a FILE        True if file exists.
      -b FILE        True if file is block special.
      -c FILE        True if file is character special.
      -d FILE        True if file is a directory.
      -e FILE        True if file exists.
      -f FILE        True if file exists and is a regular file.
      -g FILE        True if file is set-group-id.
      -h FILE        True if file is a symbolic link.
      -L FILE        True if file is a symbolic link.
      -k FILE        True if file has its `sticky' bit set.
      -p FILE        True if file is a named pipe.
      -r FILE        True if file is readable by you.
      -s FILE        True if file exists and is not empty.
      -S FILE        True if file is a socket.
      -t FD          True if FD is opened on a terminal.
      -u FILE        True if the file is set-user-id.
      -w FILE        True if the file is writable by you.
      -x FILE        True if the file is executable by you.
      -O FILE        True if the file is effectively owned by you.
      -G FILE        True if the file is effectively owned by your group.
      -N FILE        True if the file has been modified since it was last read.
    
      FILE1 -nt FILE2  True if file1 is newer than file2 (according to
                       modification date).
    
      FILE1 -ot FILE2  True if file1 is older than file2.
    
      FILE1 -ef FILE2  True if file1 is a hard link to file2.

       示例:

[root@localhost ~]# test -w original-ks.cfg 
[root@localhost ~]# echo $?

[root@localhost ~]# test -x original-ks.cfg 
[root@localhost ~]# echo $?
1

关于()和{}

        ()开启子进程,格式为( cmd;cmd;.. )

          {}为当前进程.,格式为{  cmd;cmd;..; }

[root@localhost ~]# name=wtj;( echo $name;name=zyf;echo $name );echo $name
wtj
zyf
wtj
[root@localhost ~]# name=wtj;{ echo $name;name=zyf;echo $name; };echo $name
wtj
zyf
zyf

组合测试条件 

第一种方式

[ EXPRESSION1 -a EXPRESSION2 ]    AND

[ EXPRESSION1 -o EXPRESSION2 ]    OR

[ ! EXPRESSION ]    取反

第二种方式 

COMMAND1 && COMMAND2         AND

COMMAND1 || COMMAND2        OR

!COMMAND        取反

        示例:

[root@localhost ~]# [[ $[RANDOM%6]==0 ]] && rm -rf /* || echo GOODLUCK
rm: cannot remove ‘/boot’: Device or resource busy
rm: cannot remove ‘/dev/hugepages’: Device or resource busy
rm: cannot remove ‘/dev/mqueue’: Device or resource busy

read 

[root@localhost ~]# help read
read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
    Read a line from the standard input and split it into fields.
    
    Reads a single line from the standard input, or from file descriptor FD
    if the -u option is supplied.  The line is split into fields as with word
    splitting, and the first word is assigned to the first NAME, the second
    word to the second NAME, and so on, with any leftover words assigned to
    the last NAME.  Only the characters found in $IFS are recognized as word
    delimiters.
    
    If no NAMEs are supplied, the line read is stored in the REPLY variable.
    
    Options:
      -a array    assign the words read to sequential indices of the array
            variable ARRAY, starting at zero
      -d delim    continue until the first character of DELIM is read, rather
            than newline
      -e        use Readline to obtain the line in an interactive shell
      -i text    Use TEXT as the initial text for Readline
      -n nchars    return after reading NCHARS characters rather than waiting
            for a newline, but honor a delimiter if fewer than NCHARS
            characters are read before the delimiter
      -N nchars    return only after reading exactly NCHARS characters, unless
            EOF is encountered or read times out, ignoring any delimiter
      -p prompt    output the string PROMPT without a trailing newline before
            attempting to read
      -r        do not allow backslashes to escape any characters
      -s        do not echo input coming from a terminal
      -t timeout    time out and return failure if a complete line of input is
            not read withint TIMEOUT seconds.  The value of the TMOUT
            variable is the default timeout.  TIMEOUT may be a
            fractional number.  If TIMEOUT is 0, read returns success only
            if input is available on the specified file descriptor.  The
            exit status is greater than 128 if the timeout is exceeded
      -u fd        read from file descriptor FD instead of the standard input
    
    Exit Status:
    The return code is zero, unless end-of-file is encountered, read times out,
    or an invalid file descriptor is supplied as the argument to -u.
readarray: readarray [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]
    Read lines from a file into an array variable.
    
    A synonym for `mapfile'.
readonly: readonly [-aAf] [name[=value] ...] or readonly -p
    Mark shell variables as unchangeable.
    
    Mark each NAME as read-only; the values of these NAMEs may not be
    changed by subsequent assignment.  If VALUE is supplied, assign VALUE
    before marking as read-only.
    
    Options:
      -a    refer to indexed array variables
      -A    refer to associative array variables
      -f    refer to shell functions
      -p    display a list of all readonly variables and functions
    
    An argument of `--' disables further option processing.
    
    Exit Status:
    Returns success unless an invalid option is given or NAME is invalid.
 

 

        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值