Bash Shell Script Programming Learning Summary

Source: Internet
Author: User
Tags arithmetic stdin

shell scripting
Compiler ------- interpreter
Static language: compiled language, strongly typed (variable); converted to executable format in advance. C / C ++ / JAVA / C #
Dynamic language: interpreted language, weakly typed. Explain while changing execution. PHP, SHELL, python, perl
Process-oriented: shell, c; Object-oriented: java, python, perl, c ++
Variable assignment: VAR_NAME = VALUE;

bash variable types:
    Environment variable: The scope is the current shell process and its child processes.
        export VARNAME = VALUE or VARNAME = VALUE export VARNAME "Export" is defined as an environment variable.
        The script starts a subshell process when executed:
        [[email protected] ~] # NAME = LINJUNBIN
        [[email protected] ~] # export NAME
        [[email protected] ~] # echo $ NAME
        LINJUNBIN
        [[email protected] ~] # bash // Switch to a subshell;
        [[email protected] ~] # echo $ NAME // The environment variable is still valid.
        LINJUNBIN

    Local variables (local variables):
        The entire bash process: local variable: VARNAME = VALUE
        Local variables: The scope is valid for the current code segment. local VARNAME = VALUE
    Position variable:
        $ 1, $ 2, ....
    Special variables: (built-in bash): $ ?: the execution status of the previous command, the status value;
        There are generally two return values for program execution; execution status $? = 0-255
        0: Correct execution; 1-255: Incorrect execution;
        1,2,127: Reserved by the system.
        $ ?: the status code of the last command execution;
        $ #: Number of parameters
        $ *: Parameter list
        [email protected]: Parameter list

Reference variable: $ {VAR_NAME}, reference the variable.
    [[email protected] ~] # echo "there are some $ {ANIMAL} s."
    there are some PIGs.
    [[email protected] ~] # echo ‘there are some $ {ANIMAL} s.’
    there are some $ {ANIMAL} s.
    Note: ‘‘ The difference between single quotes and “” double quotes.

Output redirection:
    >: >>: 2>: 2 >>, &>
Enter:
    / dev / null: software device; / dev / null: data black hole;
    eg: Determine whether a user is included.
        [[email protected] ~] # id student &> / dev / null
        [[email protected] ~] # echo $?
        1
Undo variable:
    unset VARNAME without adding $;
View variables:
    Use the set command; set: contains environment variables and local variables;
    View environment variables: printenv, env, export; all three are fine.
eg:
    [[email protected] ~] # ANIMALS = pig
    [[email protected] ~] # ANIMALS = $ ANIMALS: goat
    [[email protected] ~] # echo $ ANIMALS
    pig: goat
Scripting: stacking of commands,
Determine if the user exists: id user1 &> / dev / null && echo "hello user1";
    [[email protected] test] # id root &> / dev / null && echo ‘root’
    root
shell condition judgment
Determine the execution result $? To determine the execution status code to determine whether the execution was successful or failed.
Integer test:
    -eq: test whether two integers are equal;
    -ne: test whether two integers are not equal, not equal, true; equal, false;
    -gt: test whether one number is greater than another number;
    -lt: test if one number is less than another number;
    -ge: greater than or equal to;
    -le: less than or equal to;
    eg:
            [[email protected] test] # A = 3
            [[email protected] test] # B = 4
            [[email protected] test] # [$ A -eq $ B]
            [[email protected] test] # echo $?
            1
            [[email protected] test] # B = 3
            [[email protected] test] # [$ A -eq $ B]
            [[email protected] test] # echo $?
        0
Character test:
File test:

Conditional test expression: Note: Spaces are required on both sides.
    [expression expression], [[expression]], test expression
expression:

Logical relationship between commands;
    Logical AND: &&, the first condition is false and the second condition does not need to be executed, both must be true.
    Logical OR: || The first condition is false, and the second condition must be judged. One of the two can be true.
    eg: if user user6 does not exist, add user user6
        ! id user6 &> / dev / null && useradd user6
        id user6 &> / dev / null || useradd user6
LINE = `wc -l / etc / inittab`; Put the result of this command in a variable.
eg: If the number of lines in the file / etc / inittab is greater than 100, a large file is displayed, otherwise a small file is displayed.
        [[email protected] test] # cat souce.sh
        #! / bin / bash
        LINES = `wc -l / etc / inittab`
        echo $ LINES
        FINLINES = `echo $ LINES | cut -d‘ ‘-f1`
        echo $ FINLINES;

        [$ FINLINES -gt 100] && echo "/ etc / inittab is a big file." || echo "/ etc / inittab is a small file"

        [[email protected] test] # bash souce.sh
        17 / etc / inittab
        17
        / etc / inittab is a small fi

eg: Add users to the system:
`! id user1 &> / dev / null && useradd user1 && echo" user1 "| passwd --stdin user1 &> / dev / null || echo‘ user1 exists`
    After adding users, pipe to passwd. Set password; output the total number of lines at the same time.
    [[email protected] test] # bash addUser.sh
    user1 exists
    39
    [[email protected] test] # cat addUser.sh
    #! / bin / bash
    ! id user1 &> / dev / null && useradd user1 && echo "user1" | passwd --stdin user1 &> / dev / null || echo ‘user1 exists’
    ! id user2 &> / dev / null && useradd user2 && echo "user2" | passwd --stdin user2 &> / dev / null || echo ‘user2 exists’
    ! id user3 &> / dev / null && useradd user3 && echo "user3" | passwd --stdin user3 &> / dev / null || echo ‘user3 exists’
    #Get the total number of rows
    LINES = `wc -l / etc / passwd | cut -d‘ ‘-f1`
    echo $ LINES;

    eg:
    # Determine whether the current user is a root user;
            [[email protected] test] # bash is_root.sh
            is root
            [[email protected] test] # cat is_root.sh
            #! / bin / bash
            USER_UID = `id -u`;
            [$ USER_UID -eq 0] && echo ‘is root’ || echo "is not root and this uid is $ {UID}"
        Note: The error is_root.sh: line 2: UID: readonly variable. The original is the same as the UID variable setting and environment variable. The main variable is named.
if condition judgment
Single branch if statement:
    if condition
    then
        statement1; statement2;
    fi
Double branch if statement:
    if judgment condition; then
        statement1; statement2; ...
    else
        statement3; statement4; ...
    fi
Multi-branch if statement
    if condition judgment 1; then
        statement1; ...
    elif judgment condition 2; then
        statement2; ...
    elif judgment condition 3; then
        statement3; ...
    ...
    else
        statement4; ...
    fi

eg:
    #Determine if a user exists:
    [[email protected] test] # bash user.sh
    user12 IS NOT exists
    [[email protected] test] # cat user.sh
    #! / bin / bash
    NAME = user12;
    if id $ NAME &> / dev / null; then
    echo "$ NAME is exists"
    else
    echo "$ NAME IS NOT exists"
    fi
    #If the user exists, display the existence, if not, add it;

eg:
#Determine if the current system has a user's default shell as bash: if there is, display it How many, otherwise it shows that there are no such users
        [[email protected] test] # ./is_bash.sh
        the shells of 10 users is bash shell
        [[email protected] test] # cat is_bash.sh
        #! / bin / bash
        #Get the default shell for bash
        grep "bash $" / etc / passwd &> / dev / null;
        RETVAL = $ ?;
        if [$ RETVAL -eq 0]; then
          USERS = `grep" \ <bash $ "/ etc / passwd | wc -l`
          echo "the shells of $ USERS users is bash shell";
        else
         echo "no bash user"
        fi
        [[email protected] test] #

#Verify that there are no blank lines in / etc / inittab, how many blank lines
        [[email protected] test] # cat has_space.sh
        #! / bin / bash
        grep "^ $" / etc / inittab &> / dev / null;
        HAS_SPACE = $?
        if [$ HAS_SPACE -eq 0]; then
        SPACES = `grep" ^ $ "/ etc / inittab | wc -l`;
        echo "total SPACES is $ SPACES LINES";
        else
        echo "no any spaces in / etc / inittab";
        fi
        [[email protected] test] #
    Note: there must be no spaces on either side of the equal sign;

#Verify that the user's uid is equal to the GID, two implementation methods
        [[email protected] test] # cat uid_eq.sh
        #! / bin / bash
        USERNAME = user1
        # USERID = `id -u $ USERNAME`;
        USERID = `grep" ^ user1 "/ etc / passwd | cut -d: -f3`
        GROUPID = `grep" ^ user1 "/ etc / passwd | cut -d: -f4`
        # GROUPID = `id -g $ USERNAME`;

        if [$ USERID -eq $ GROUPID]; then
        echo ‘Good guy’;
        else
        echo ‘Bad guy’;
        fi
#Note: date +% s represents the number of seconds since 1970 in the timestamp; man date
echo $ HISTSIZE;

#Give a file to test its existence
#Single step execution; bash -x
    eg: Test script execution. bash -x
        [[email protected] test] # bash -x file_test.sh
        + FILE = / etc / inittab
        + ‘[’ -E / etc / inittab ‘]’
        + echo OK
        OK
        [[email protected] test] #

# Given a file, if it is a normal file, it will be displayed, if it is a directory, it will be displayed, otherwise the display cannot identify the file.
    [[email protected] test] # ./file_test.sh
    common file
    [[email protected] test] # cat file_test.sh
    #! / bin / bash

    FILE = / etc / inittab

    if [! -e $ FILE]; then
    echo ‘no such file’;
    exit 6;
    fi
    if [-f $ FILE]; then
    echo ‘common file’;
    elif [-d $ FILE]; then
    echo ‘directory’;
    else
    echo ‘unknown’;
    fi
    Note: the predicate! There must be a space after it;
arithmetic operations in the shell
All variables in the shell are strings by default;
    [[email protected] test] # A = 3
    [[email protected] test] # B = 4
    [[email protected] test] # echo $ A + $ B
    3 + 4
Generally use these three methods: 1, 2, 3:
1. Arithmetic operation let:
    let C = $ A + $ B
2. [[Arithmetic operation expression]
    C = $ [$ A + $ B]
3. $ ((Arithmetic operation expression))
    C = $ (($ A + $ B))
4, expr arithmetic operation expressions, there must be spaces between the operands and operators in the expression, and use command references
    F = `expr $ A + $ B`
5, using the arithmetic unit bc
Exit script
exit: exit the script;
exit n; n is the exit status code;
If the script does not explicitly define the exit status code, then the exit code of the last command is the exit status code of the script;
Test Methods
Use square bracket test method:
[expression]: Remember to use spaces on both sides and order the test method;
[[expression]]: keyword test method;
test expression:
Only use -gt, -le, -ne, -eq, -ge, -lt: square brackets are required, others are not necessarily square brackets.
if `grep" ^ $ USERNAME \> "/ etc / passwd`; then

File test:
    -e FILE: Whether the file exists.
    -f FILE: test whether the file is a normal file
    -d FILE: test whether the specified path is a directory;
    -r FILE: test whether the current user has read permissions on the specified file
    -w FILE: test whether the current user has write permission on the specified file
    -x FILE: test if the current user has execute permission on the specified file
    eg:
    [-e / etc / inittab], [-x /etc/rc.d/rc.sysinit]
        [[email protected] test] # ./exitst_file.sh
        NO / etc / iniittab
        [[email protected] test] # cat exitst_file.sh
        #! / bin / bash

        FILE = / etc / iniittab
        if [! -e $ FILE]; then
          echo "NO $ FILE"
          exit 8;
        fi

Round: discard the content after the decimal point; /
Show history commands:
    [[email protected] test] # history | tail -1 | cut -d ‘‘ -f2
    1012
Position variable (parameter)
Position variables $ 1, $ 2, ...
./file_test.sh / etc / fstab / etc / inittab;
$ 1: / etc / fstab; $ 2: / etc / inittab;
shift: Pop the first parameter in the parameter list; equivalent to shift in the array to pop the first element;
shift n: indicates that n parameters are popped at a time;

#Judgment: Receive a parameter, display OK if an existing file, no such file if it does not exist
    eg: $ #: display the number of all parameters; $ *: parameter list [email protected]: parameter list
            [[email protected] test] # ./exitst_file.sh / etc / inittab / ffff / ttddd
            3
            / etc / inittab / ffff / ttddd
            / etc / inittab / ffff / ttddd
            OK
            [[email protected] test] # cat exitst_file.sh
            #! / bin / bash
            echo $ #
            echo $ *
            echo [email protected]

            if [! $ 1]; then
             echo ‘please add parame file’;
            exit;
            fi

            if [-e $ 1]; then
              echo "OK"
            else
              echo "no such file";
            fi
            [[email protected] test] #

#Test shift
        [[email protected] test] # ./shift.sh 1 2 3 4 5
        5
        1
        2
        4
        [[email protected] test] # cat shift.sh
        #! / bin / bash

        echo $ #;
        echo $ 1;
        shift
        echo $ 1;
        shift 2
        echo $ 1
Bash shell scripting learning summary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.