Unix Shell script programming knowledge point summary and Examples

Source: Internet
Author: User

Scripting and compilation languages:

 
 
  1. Scripting language (Bash)

  2. The scripting language is usually interpreted. It is mainly used by the interpreter to read the program code and convert it into an internal form for execution.

  3. Advantages:

  4. Objects such as files and directories can be easily processed.

  5. Disadvantages:

  6. Generally, the operating efficiency is not as high as that of compiled languages.

  7. Compiled language: (C, C ++, Java, Fortran, Ada, Pascal)

  8. Most of the compiled languages work at the underlying layer. They process byte, integer, floating point, or other objects on the machine layer.

Basic syntax format of SHELL script:

 
 
  1. The script must start #! Start with: (# cat/etc/shells)

  2. Example #! /Bin/bash (Interpreter)

  3. # Some comments can be added in the middle, such as the script usage, script functions, creation date, author, and other related information.

  4. Then grant the script execution permission, # chmod + x scripts. sh

  5. Run./scripts. sh # Or add the PATH of the script to the PATH variable. Then run the script directly using the Script Name.

  6. Script test tool bash:

  7. -N: Check whether the script has a syntax error. If yes, the error message is displayed. Otherwise, no message is displayed. (no message is the best message)

  8. -X: Check the detailed process of the script execution (usually used in troubleshooting)

  9. Exit: exit the script (its value is 0-255)

  10. If the script does not clearly define an exit code, the exit code before the script execution ends is the exit code of this script.

  11. # Echo $? # View the status code displayed in the execution result of the previous command

Summary of the logical relationship of SHELL scripts:

 
 
  1. Logic and: Symbol &&:

  2. If one of them is false, the result must be false.

  3. If the first condition result is false, the second condition does not need to be judged. The final result is displayed.

  4. If the first condition returns true, the second condition must be judged.

  5. Example:

  6. # Useradd redhat & echo "redhat" | passwd -- stdin redhat
    NOTE: If useradd redhat is successfully executed, continue to run the next command. Otherwise, it is terminated.

 
 
  1. Logic or |:

  2. If the result of one of the conditions is true, the result must be true without checking the subsequent statements.

  3. If one of the conditions is false, check the next Condition Statement.

  4. Example:

  5. # Id redhat | useradd redhat

  6. Note: If a redhat user exists, information about the redhat user is displayed; otherwise, this account is added.

  7. Example of logical and logical or combined use:

  8. # Id redhat & echo "redhat already existing" | useradd redhat

  9. Note: If the redhat user exists, it indicates that the redhat user already exists. Otherwise, add this account.

Condition judgment statement summary:

 
 
  1. Single branch if statementDual-branch if statementMulti-branch if statementCase selection statement

  2. If judgment condition; then if judgment condition; thencase $1 in

  3. Statement string)

  4. .................... Statement ;;

  5. Fi else elif judgment condition; then string2)

  6. Statement ;;

  7. ....................)

  8. Fi elif judgment condition; then statement ;;

  9. Statement esac

  10. .........

  11. Else

  12. Statement

  13. Fi

Example:

650) this. width = 650; "border =" 0 "src =" http://www.bkjia.com/uploads/allimg/131228/014G614N-0.png "/>

 
 
  1. Script analysis:

  2. Main function: pass a different parameter to create, add, and delete a user.

  3. Detailed description:

  4. When the -- add parameter is passed to this script, this script is used to add the specified user. If the added user exists, the user is prompted to exist, otherwise, add a specified user and create a user-based password;

  5. When we pass the -- del parameter to this script, this script will delete the user we specified. If yes, this user will be deleted. Otherwise, the system will prompt that the user does not exist.

  6. When we pass the -- help parameter to this script, this script will give us how to use the actual script.

  7. When other parameters are passed, an unrecognized option is displayed.


POSIX summary:

 
 
  1. 0: ## status of successful commands

  2. > 0: # during redirection or word expansion (~ , Variable, command, arithmetic expansion, and word cutting failed.

  3. 1-125 ## status of Command failure.

  4. 126 ## the command is found, but the state displayed when the file cannot be executed

  5. 127 ## the status shown when the command cannot be found

  6. > 128 ## the command died after receiving the signal

Replacement operator Summary (variable assignment ):

 
 
  1. $ {Varname:-word}

  2. If varname exists and is not null, its value is returned; otherwise, word is returned;

  3. Purpose: If the variable is not defined, the default value is returned.

  4. Example: If count is not defined, the value of $ {count:-0} is 0.

  5. $ {Varname: = word}

  6. If varname exists and is not null, its value is returned. Otherwise, varname is set to word and its value is returned;

  7. Purpose: If the variable is undefined, set the variable to the default value.

  8. Fan lie: If count is not defined, the value of $ {count: = 0} is 0.

  9. $ {Varname: + word}

  10. If varname exists and is not null, word is returned; otherwise, null is returned;

  11. Purpose: To test the existence of a variable.

  12. Example: If count has been defined, the value of $ {count: + 1} is 1.

  13. $ {Varname :? Message}

  14. If varname exists and is not null, its value is returned; otherwise, varname: message is displayed and the current command or script is exited;

  15. Purpose: To capture errors caused by undefined variables.

  16. Example: If count is not defined, $ {count :? "Undefined! "}: Count: undefined!

Summary of pattern matching operators:

 
 
  1. Assume that the path variable value is:/etc/sysconfig/network-scripts/ifcfg-eth0.text.bak

  2. $ {Variable # pattern }:

  3. If the pattern matches the beginning of the variable value, the shortest part of the matching is deleted and the remaining part is returned;

  4. Example: The echo $ {path #/*/} value is etc/sysconfig/network-scripts/ifcfg-eth0.text.bak

  5. $ {Variable # pattern}

  6. If the pattern matches the beginning of the variable value, the longest part of the match is deleted and the remaining part is returned;

  7. Example: echo $ {path #/*/} is a ifcfg-eth0.text.bake

  8. $ {Variable % pattern}

  9. If the pattern matches the end of the variable, the shortest part of the matching is deleted and the remaining part is returned;

  10. Example: The echo $ {path %. *} value is/etc/sysconfig/network-scripts/ifcfg-eth0.text

  11. $ {Variable % pattern}

  12. If the pattern matches the end of the variable, the longest part of the matching is deleted, and the remaining part is returned.

  13. Example: The echo $ {path %. *} value is/etc/sysconfig/network-scripts/ifcfg-eth0

  14. $ {# Variable}

  15. Length of characters that show variable values

Summary of common loop statements in Shell scripts:

 
 
  1. For Loop while loop until Loop

  2. For variable in list; do while condition (condition); do until condition; do

  3. Command... statements

  4. Done


  5. While loop: as long as the condition is met, while Loops

  6. Until loop: as long as the condition does not meet the condition, until will loop

Test command

 
 
  1. The test command can handle all kinds of work in shell scripts. Instead of general output, it can use the exit state. test accepts different parameters and controls which test is to be executed.

  2. Syntax:

  3. Test [expression]

  4. Test [[expression]

  5. Purpose:

  6. To test the conditions in the shell script, return the result through the exit status.

  7. Behavior mode:

  8. Test is used to test the attributes, comparison strings, and comparison numbers of a file.

  9. Main options and expressions:

  10. String is not null

  11. -B file is a block device file (-B)

  12. -C file is a character device file (-c)

  13. -D file: Directory (-d)

  14. -E file: whether the file exists

  15. -F file is a general file (-)

  16. -G file has its setgid bit.

  17. -H file is a symbolic link.

  18. -R file is readable.

  19. -S file is socket

  20. -W file is writable.

  21. -X file is executable, or file is a directory that can be searched

  22. S1 = s2 s1 and s2 strings are the same

  23. S1! = S2 s1 and s2 strings are different

  24. N1-eq n2 integer n1 is equal to n2

  25. N1-ne n2 integer n1 is not equal to n2

  26. N1-lt n2 integer n1 less than n2

  27. N1-gt n2 integer n1 greater than n2

  28. N1-le n2 integer n1 is less than or equal to n2

  29. N1-ge n2 integer n1 greater than or equal to n2

  30. -N string is not null

  31. -Z string is null special parameter variable

  32. Some special variables in bash shell record the number of command line parameters. For example, $ #

  33. You can only count the number of parameters entered in the command line, and test each parameter differently. Bash provides a special variable for this purpose, that is, the $ # mentioned above #

  34. $ # Description

    1. $ # The number of command line parameters that the special variable contains when the script is running. You can call this special variable anywhere in the script to call $ # to calculate the number of parameters.

  35. Example:

    1. Vim Count. sh

      #! /Bin/bash

      # Script Name: Count. sh

      # Count Parameters number


      Echo There were $ # parameters.


      Chmod + x Count. sh

      ./Count. sh 1 2 3

      There were 3 parameters.


Next let's talk about $ {! #} Role?

Since the $ # variable contains the total number of parameters, then $ {! #} You can call the variable name of the last parameter.

Example:

Vim Count-1.sh.

#! /Bin/bash

# Script Name: Count-1.sh

# Print last parameter

Params =$ #

Echo "The last parameter is" $ params"

Echo "The last parameter is" $ {! #}"

: Wq


Chmod + x Count-1.sh

/Count-1.sh 1 2 3

The last parameter is 3

The last parameter is 3








This article is from the "See you next year CA" blog, please be sure to keep this source http://guodayong.blog.51cto.com/263451/1188606

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.