Bash script Programming Step-by-step article

Source: Internet
Author: User
Tags first string

Bash script programming Step-by-step article

function, array, string manipulation


function: functions in scripting are fundamentally different from the functions in our math. The functions here are mainly for the purpose of implementing procedural programming code reuse. For example, a function to calculate a number, when we need to use the calculation of numbers, call this function directly instead of every time the number must be re-written. Therefore, the main functions of the function can be summed up as follows: It is easy to implement modular programming, easy to reuse code, and make the program concise. We define functions, which can be divided into two different structures. The first function structure, which declares a function, followed by the function name. The function body is enclosed in curly braces. The second structure is to use the function name and parentheses (), the function body is still written in curly braces, both of the optional.

function F_name {functional body} or f_name () {function Body}

Understand the structure of the function and see how we use the function in particular. The function itself is a function module to implement some function. Therefore, when writing the function body, as long as the specific function can be fully implemented, and can satisfy the multi-party invocation. Let me give you an example: we want to use the function to achieve the following function, the script runs the output of a hint, the user is required to give a user name. If the user does not give a user name, the error message returns a value of 1, and an error message is given if an incorrect user name is given. Continue to allow users to access the user name. If the user gives a user name correctly, the user's shell type is output, and the user enters quit to implement the exit.

#!/bin/bash#showuserinfo ()  {    [ $# - Lt 1 ] && return 1    ! id $1 &>  /dev/null && return 2    grep  "^$1\>"  /etc/ passwd | cut -d: -f7    [ $? -eq 0 ] & & return 0 | |  return 3}while true; do    read -p  "enter a  username:  " username    [ " $username " ==  ' Quit '  ] & & break    showuserinfo  $username     [ $? -ne  0 ] && echo  "There is something wrong." Done 

Here is a detailed analysis of this example: 1. In the function there is a return 1,3, and these are actually the functions returned values. What he responds to is the result of the function's execution. In addition, the function also has exit status code, the exit status code of the function is the same as the exit status code of the script is the same selection method. Are the results of the execution status of their last statement (note that the execution status results). We can also customize it. As the example of our face reading, we write return #. Here # requirements between [0-255]. function body during execution, once a return is encountered, it will stop running. 2. We are here to display a function of the user shell type, which is interactively entered by the script when it executes. It is clear that the function can also implement the passed parameters. $1,$#,$* and other variables to master OH. 3. The call to the function here sees the case, which is to implement the call directly using the name of the functor.

Note: When we use variables in a function, be aware of declaring local variables. Local Var=value, otherwise, if the function changes in the function body, it causes the value of other functions with the same name to change.

Recursive invocation of a function, the recursive invocation is actually the function itself called itself. It seems a little abstract to say so. Imagine the factorial expression in math. 10! N (n-1)! N (n-1) (n-2)! ... This expression is the most typical recursion. Let's take a look at how the recursive invocation of a function is implemented.

Fact () {if [$1-eq 0-o $1-eq 1]; Thenecho 1else echo $[$1*$ (fact $[$1-1])]fi}

Note: Recursive invocation of a function is computationally inefficient for a computer because he stores all the results of the run in memory, until it runs to the last expression, and then outputs the data from scratch.

Array of functions: an array of functions can be understood as a contiguous number of independent memory spaces, and each memory space is actually equivalent to a specific variable. These so-called variable variables we call the array elements of the function.

two. Array element composition: array name + index number (index number is zero number) For example: array[0]= "Hello" here the array name is array,[0] that is the index number.

Array usage: First declare an array, declare-a arrar_name. This is critical and cannot be omitted, because if not declared. Because if not declared, the function will treat this as a variable. Since an array is a contiguous space storage unit, he needs to be assigned a value. Arrays are assigned in a variety of ways:

(1) Assign only one element at a time array[index]=valuea[0]= "abc" (2) assigns all elements array= ("Mon" "Tue" "Wed") (3) assigns an index to the assignment array= ([0]= "Sun" [1]= "Mon" [5]= "Fri") (4) Read-a ARRAY

after the assignment is implemented, it is called normally. Reference array element, ${array element}=${arrsy[0]}. This is a call to a specific array element in a group. The length of the array we are using: ${#ARRAY [*]} or to implement. An example: define an array whose elements are the names of all files ending with. Log in the/var/log directory, and then display the contents of the elements with an odd index;

#!/bin/bash#declare-a filesfiles= (/var/log/*.log) for i in ' seq 0 $[${#files [*]}-1] '; Do [$[$i%2]-ne 0] && Echo ' $i: ${files[$i]} "done

An array of elements related to handling problems:

1. Pick one with element: ${array[i]}

2. Select a number of successive elements: ${array[@]:offset:number} Here offset refers to the number of offsets from the beginning of the array, and number refers to how many are taken starting from the index number.

3. Pick an element starting at the end of all elements: ${array[@]:offset} This means that all elements from the beginning of the specified index number are taken out.

4. Use all elements: ${array[@]}

5. Append an element from the array: array[${#ARRAY [@]}]

6. Remove an element from the array: unset Array[i]

Associative arrays: Associative arrays differ from arrays in that they are declared as-A; and you can customize any string as an index such as:

Declare-a Week

week= ([mon]= "Monday" [tue]= "Tuesday") This time the index is no longer a number.

Three. String manipulation:

We know that for text, you can use tools like sed to find the line or word you want. This is very handy, so we have a similar way of dealing with strings.

Slice of string:

String slicing format: ${var:offset:lenth} Here The format is very similar to the selection of the array, but the Var here is not an array but represents a variable such as: A= "Hello,world", ${a:5:2} result is:, W.

take the last few characters of the string: ${var:-lenth} For example: A= "Hello,world", ${a:-2} The result is LD. Note: There are spaces after the colon;

To take a string based on a pattern:

1.${var#*word}: Where word can be any of the specified characters that you want to find. Meaning: From left to right, delete to find the var variable stored in the character, the first occurrence of word where. For example:

# mypath= ' Sysconfig/network-scripts/ifcfg-eth0 '
# echo ${mypath#*/}
Network-scripts/ifcfg-eth0

2.${var##*word}: Where word can be any character specified, meaning: From left to right, delete the var variable stored in the character until the last occurrence of word.

# mypath= '/sysconfig/network-scripts/ifcfg-eth0 '
# echo ${mypath##*/}
Ifcfg-eth0

3.${var%word*}: From right to left, delete the first word that appears at the beginning of the character until all the characters in the tail;

# mypath= '/sysconfig/network-scripts/ifcfg-eth0 '
# echo ${mypath%/*}
/sysconfig/network-scripts

4.${var%%word*}: From right to left, delete all characters at the beginning of the last word occurrence until the end of the character;

Understanding Memory: Here can remember, #表示从左至右, so * to put on the left side of Word to delete the section, 1 # means the first match to the place, # #就表示最后一次匹配到的地方. % is right-to-left, so * to the right of word to indicate the part to be deleted, the same first% means the first match to the place, the percent of the last to be matched to the place.

Find and Replace:

${var/pattern/substi}: Find the string represented by Var, the first string to be matched by pattern, and replace it with Substi;

For example:

# mypath= '/sysconfig/network-scripts/ifcfg-eth0 '
# echo ${mypath/\/sysconfig/etc}
Etc/network-scripts

${var//patten/substi}: Find the string represented by Var, all the strings that are matched by pattern, and replace them with Substi;


${var/#pattern/substi}: The pattern is anchored at the beginning of the line to match the patterns to the string represented by Var, and if it matches, it is replaced with substi;

# mypath= '/sysconfig/network-scripts/ifcfg-eth0 '
# echo ${mypath/#\/sysconfig/etc}
Etc/network-scripts

${var/%pattern/substi}: The pattern is matched to the string represented by Var at the end of the line, and replaced by substi if it matches;

The pattern here can be used?, * meta-characters;

Find and delete:

${var/pattern}: Delete pattern match to the first occurrence;

${var//pattern}: Delete all occurrences of pattern matching;

${var/#pattern}: Delete pattern match to place at beginning of line

${var/%pattern}: Delete pattern matches to the end of line

This can be combined with the previous replacement memory, the understanding that the replacement is empty, then it is deleted.

String Case Conversion:

${var^^}: Lowercase-to-uppercase

Mypath= '/sysconfig/network-scripts/ifcfg-eth0 ' echo ${mypath^^}/sysconfig/network-scripts/ifcfg-eth0


${var,,}: uppercase-to-lowercase

Variable assignment:

${var:-word}: Returns word if Var is empty or not set, otherwise returns the value in Var;

${var:=word}: Returns word if Var is empty or not set, and assigns Word to Var; otherwise, returns the value in Var;

${var:?err_info}: Returns an error message if Var is empty or not set, otherwise returns the value of Var itself;

${var:+word}: Returns word if VAR has its own normal data;




























This article is from the "I and Linux years" blog, please be sure to keep this source http://guanqianjian.blog.51cto.com/9652236/1587052

Bash script Programming Step-by-step 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.