Linux system study notes: BASH programming

Source: Internet
Author: User
Linux system learning notes: BASH programming uses var (elementelement...) to create array variables. When referencing elements in an array, use $ {var [I]}, I as the subscript, subscript @ to copy the original array, and subscript * to copy the original array, but when double quotation marks are added, it uses the original array as... linux system learning notes: BASH programming using var = (element ...) create an array variable. When referencing elements in an array, use $ {var [I]}, I as the subscript, subscript @ to copy the original array, and subscript * to copy the original array, when double quotation marks are added, the original array is used as an element. Var [I] = value can be used to assign values to a single element in the array. $ {# Var [I]} returns the length of the element, and $ {# var [*]} returns the number of elements in the array. $ Array = (Alex Harry Nancy) $ arr1 = ("$ {array [@]}") $ arr2 = ("$ {array [*]}") $ declare-adeclare-a arr1 = '([0] = "Alex" [1] = "Harry" [2] = "Nancy ") 'destare-a arr2 = '([0] = "Alex Harry Nancy ") 'destare-a array = '([0] = "Alex" [1] = "Harry" [2] = "Nancy ") '$ array [1] = Jerry $ echo $ {array [*]} Alex Jerry Nancy $ echo $ {array [@]} Alex Jerry Nancy $ echo $ {# array [*] }$ {# array [1]} 3 5 the scope of the variable is the current script, you can use export to declare a variable. it makes the variable of the parent process available to the child process. The variables in the function are not local by default, and the scope is also the current script. to avoid conflicts, you can use typeset to declare it as a local variable. $ {# Var} returns the length of the variable. $ {Var:-default} uses the value of the variable. if the value is null or not assigned a value, the default value is used. $ {Var: = default} is similar to the former, but it also assigns the default value to the variable when the value is null or not assigned a value. $ {Var :? Message} displays the error message when the value is null or not assigned a value. If no message is provided, the default error message is displayed. $ Cd $ {dir :? $ (Date + % T) error, dir not set .} -bash: dir: 10:15:29 error, dir not set.: You can assign values to the variable but do not execute it. Usually, you can use $ {var: = default} to set the default value for the variable. BASH supports string matching in the form of $ {varOPpattern}, OP is: # Remove the minimum matching prefix, # Remove the maximum matching prefix, and % remove the minimum matching suffix, % remove the maximum matching suffix. $ File =/home/yeolar/. sh $ echo $ {file ##/ */}. sh $ echo $ {file %/*}/home/yeolar (var = base # n) syntax can assign values to variables with other bases. $ (N = 8 #0101); echo $ n65 location parameter save command and command parameters. You can use set to change the content of the location parameter, but cannot change the command name in the script. $ # Number of saved parameters, $0 save command name, $1-$ n save command parameters, $ @ and $ * save all parameters, similar to array variables, when double quotation marks are added, $ * is used as a parameter, and $ @ is used as a set of parameters. Shift Left parameter. Set initialization parameters (when set does not have parameters, the configured shell variables are displayed, and you can also use it to set shell features ). $ Cat. shecho "cmd: $0, args: $ *, argnum: $ #" echo "first arg: $1" echo "shift args... "shiftecho" cmd: $0, args: $ *, argnum: $ # "echo" first arg: $1 "set" $ @ "echo" first arg: $1 "set" $ * "echo" first arg: $1 "set a B cecho $ * $ bash. sh x y zcmd:. sh, args: x y z, argnum: 3 first arg: xshift args... cmd:. sh, args: y z, argnum: 2 first arg: yfirst arg: y za B c and some special parameters: $ Save the PID of the current (shell) process, $! Save the PID of the process recently transferred to the background, $? Save the return status code of the previous command. Special parameters and location parameters cannot be changed through the value assignment statement. You can use let "expr" or (expr) expressions to evaluate arithmetic expressions. multiple expressions can be separated by spaces and commas. $ X = 1 y = 1 z = 0 $ let "x = x * 10 + y" z = z + 1 $ echo $ x $ y $ z11 1 $ (x = x * 10 + y, z = z + 1) $ echo $ x $ y $ z111 1 2 conditional expressions use [[expr] to evaluate. There is a special operator =, which can be used in a condition expression to determine equality. The BASH operator supports most operators in the C language. some operators add meanings in some specific syntax structures, such as pipelines. Control flow if... thenif... the then syntax is as follows: if test-command then command [elif test-command then command...] [else command] fi is often used to reduce indentation; it writes then to the last line. Test-command is a test command. you can use the test command for testing, but it is generally used as a synonym []. # Check the number of parameters if [$ #-eq 0]; then # is equivalent to: if test $ #-eq 0; then echo "Usage: cmd arg "1> & 2 exit 1fi: -eq equals-ne not equal to-gt greater than-ge Greater than or equal to-lt less than-le less than or equal to strings can be used = and! =. Below are some file-related check options: -e check whether the file exists-d check whether the file exists and is a directory-f check whether the file exists and is a common file-s check whether the file exists and is greater than 0 bytes-r check whether the file exists the syntax for existence and readable-w checks whether the file exists and writable-x checks whether the file exists and can execute forfor is as follows: for var [in list] do commanddoneseq is a list-ready expression. The in list can be omitted. in this case, the list is the command parameter, that is, $ @. # Whos script: print the username and full name Usage: whos user... for user; do gawk-F: '{print $1, $5}'/etc/passwd | grep-I "$ user" donewhile and untilwhile are similar to, the difference is that until tests after the do branch is executed, and the test result is a false cycle. if the test result is true, it jumps out of the loop. Syntax: while test-commanddo commanddone until test-commanddo commanddone # Find the spelling-wrong word while read line; do if! Grep "^ $ line $" "$1">/dev/null; then echo $ line fidone # name rightname = yeolaruntil ["$ name" = "$ rightname"]; do echo-n "Guess:" read namedoneecho "Good, you 've got it. "break and continuebreak and continue can be used to jump out of the loop and continue the next loop in the for, while, and until statements. Casecase is used for multi-channel selection. Syntax: case test-command in pattern) command; [pattern) command;...] esacpattern can be used to match any string ,? Match a single character. [...] provides matching characters. | separate different options. # Command select echo-e "\ ncmds: A for date, B for who, C for pwd. \ n "echo-n" Enter A, B or C: "read ccase" $ c "in a | A) date; B | B) who; c | C) pwd; *) echo "Invalid choice: $ c"; esacselectselect displays a menu, assigns the corresponding value to the variable according to the user's choice, and then runs the command. To exit select, you can use break or exit the entire script. Select var [in list] do commanddone is the same as for. if in list is omitted, it is replaced by a command parameter. The select prompt set for the PS3 is generally set as the required prompt statement. # Command menu PS3 = "Choose what you want to do:" select c in date who pwd exit; do if ["$ c" = ""]; then echo-e "Invalid choice. \ n "continue elif [$ c = exit]; then echo" quit "break fi echo" You choose: $ c "if [$ c = date]; then date elif [$ c = who]; then who elif [$ c = pwd]; then pwd fi echo "" done file descriptor in BASH, execute operations related to the file descriptor using the exec command: exec n> outfile open outfile as the output file, assign the file descriptor nexec n <infile open infile As the input file, assign the file descriptor nexec n <& m to open or redirect the file descriptor n, as a copy of the file descriptor m exec n <&-disable the file descriptor n built-in command many BASH built-in commands have been mentioned earlier. here is a summary and supplement.: Returns 0 or true (empty internal command ). use shell scripts as part of the current process to execute bg pending task break jump out of loop cd change working directory continue next loop echo show eval scan and computation command line exec execute shell script or program and replace exit current process exit from current shell exit export put variable in called environment fg move background task to foreground getopts analysis read shell script parameter jobs list background task kill send to process or job the signal pwd indicates that the current working directory read reads a row of readonly from the standard input and declares that the variable is a read-only set to list all the variables, set shell features, set the command line parameter shift left shift command line parameter test compare times to display the running time of the current shell and its sub-processes trap capture signal type to display information about the command provided by the parameter umask to return the mask created by the file, set mask unset delete variable or function wa It supports the following options when the background process ends: -The words entered by a array are used as the array element.-d delim uses delim instead of line feed to terminate the input.-e uses the Readline library to obtain the input (when the input comes from the keyboard) -n num: returns the-p prompt with the prompt as the input prompt after reading the num characters-s does not print the character on the terminal-un has a special input from a file with the file descriptor n REPLY, save the read input. The getopts syntax is getopts optstr var [arg...], optstr provides valid letter options. var stores the value of each received option. arg is the parameter to be processed. if it is omitted, the command line parameter is processed by default. Optstr starts with: the script is responsible for generating error information; otherwise, it is generated by getopts. Optstr follows a letter: indicates the option acceptance value, and OPTARG saves the option-related value. The index of the OPTIND storage option. the start value is 1. Exec is both executable script and executable program. it does not create a new process and replaces the current (shell) process with the content to be executed. Trap ['command'] [signal] is used to capture signals and execute commands. if there is no command, reset the trap. Trap ''2 15 # capture and ignore the interrupt trap 'echo Interrupted.; exit 1' INT # capture the interrupt, print the information, and exit kill to send a signal to the process, such as terminating the process. The process content will be detailed later. Shell scripts can be compiled based on the content introduced in this article and the knowledge of the first two articles. It can be used like a Python script #! Define the interpreter for the script. #! /Bin/bash # OR :#! /Usr/bin/env bash
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.