Bash programming arrays and string handling

Source: Internet
Author: User
Tags rand

Bash programming arrays and string handling



Directory


Note Date 20180405


Array

Fame (Create) array declare-a array_name

Assignment of array elements array_name= ("VAL1" "VAL2" "VAL3" ...)

Referencing an array element: ${array_name[index]}


Bash's string processing tool

String Slice ${var:offset:number}

Pattern-based String ${var#*word}

Find the value of the replacement variable ${var/pattern/match}

Find and delete certain characters of a variable ${var/#pattern}

Character Case Conversion ${var^^}

Judgment variable Assignment ${var:-value}


Create temporary File command

Mktemp

Install


Exercise: Write a script (copy the command and the library it depends on)






Variables: Storing the memory space of a single element

Array: A contiguous memory space that stores multiple elements

The array reference is starting from number 0 and is a numeric index

Note: Indexes can also support the use of custom formats, not just numeric formats.

Referencing an element in an array: ${array_name[index]}


An array of Fame (creation):

Declare-a Array_Name

Declare-a array_name associative array;



Assignment of array elements:

1. Assign only one element at a time

Array_name[index]=value

Example: weekdays[0]= "Sunday"

Weekdays[4]= "Thursday"

2. Assign all elements at once:

Array_name= ("VAL1" "VAL2" "VAL3" ...)

You can use command substitution to assign values such as: Testa= ($ (LS/))

Then use this command to view the full value of this array echo ${testa[*]}

3. Assigning only specific elements

Array_name= ([0]= "VAL1" [3]= "VAL3" ...)


4. Using an interactive assignment to an array

Read-a ARRAY

Add a space between each element



Referencing an array element: ${array_name[index]}

Note: Omitting [INDEX] means referencing an element with subscript 0


Length of the reference array (number of elements in the array): ${#ARRAY_NAME [*]}, ${#ARRAY_NAME [@]}


Example: Generate 10 random numbers into an array and find its minimum value


#!/bin/bash

#

Declare-a Rand

Declare-i minum=0


For i in {1..10}; Do

rand[$[$i -1]]= $RANDOM

echo ${rand[$[$i-1]]}

[$MiNum-eq 0] && minum=${rand[$[$i-1]}

[${rand[$[$i-1]]}-lt $MiNum] && minum=${rand[$[$i-1]}


Done

echo "Min: $MiNum"



All elements ${array_name[*]} ${array_name[@]}


Array Slice ${array[@]:offset:number}

Offset: Number of elements to skip

Number: The amount of the element to be fetched, all elements after the offset: ${array[@]:offset}


Append an element to an array array[${#ARRAY [*]}]


Delete an element in an array unset Array[index]



Bash's string processing tool

String slices:

${var:offset:number}

Remove the rightmost character of the string: ${var:-lengh}

Note: You must have a white space character after a colon


such as: Chart=balish

Echo ${chart:offset:2}

Ba


echo ${chart:-2}

Sh


Based on pattern fetching string

${var#*word} where word can be any of the specified characters

Function: From left to right, find the string stored in var variable, first occurrence word character, and left to right

Delete character to first occurrence word prompt (Note: Word characters will also be deleted)


# Chart=bllllish

# echo ${chart#*l}

Lllish


${var##*word}

Function: From left to right, find the var variable stored in the string, the last occurrence of word character, and left to right

Delete Word Fu Zhi word word prompt last occurrence (note: Word characters are also deleted)


# Chart=bllllish

# echo ${chart##*l}

Ish

${var%word*}

Function: From right to left, find the string stored in the var variable, the first word character appears, and right-to-left

Delete character to first occurrence word prompt (Note: Word characters will also be deleted)


# char= "/var/log/message"

# echo "${char%/*}"

/var/log


${var%word*}

Features: From right to left, find the string stored in the var variable, the last Word character, and right-to-left

Delete character to first occurrence word prompt (Note: Word characters will also be deleted)


# char= "/var/log/messssssssage"

# echo "${char%%s*}"

/var/log/me



Find the value of a replacement variable

You can replace the string found in a variable with a different string


${var/pattern/match}

Function: Finds the first character in a var variable that is pattern-matched and replaces its character with match


# char= "Linuuuuuuuuux Machine"

# echo "${char/u/u}"

Linuuuuuuuuux Machine

${var//pattern/match}

Function: Find all the characters in the Var variable that are pattern matched and replace their characters with match


# char= "Linnnnnnnnnnx Machinnnnnnne"

# echo "${char//n/n}"

Linnnnnnnnnnx Machinnnnnnne


${var/#pattern/match}

Function: Find the first character in the Var variable that the line is pattern to, and replace its character with match


# char= "Root:admin:123:root"

# echo "${char/#root/root}"

Root:admin:123:root


${var/%pattern/match}

function: Find var variable the end of the line is the pattern match to the character, and match to replace its characters


# char= "Root:admin:123:root"

# echo "${char/%root/root}"

Root:admin:123:root


Find and delete certain characters of a variable

You can delete a string that is found in a variable

The example here is no longer similar to the lookup substitution above, except that no substitution is specified in the back, and the found delete

${var/pattern} finds the first character in a variable that is pattern matched to the left-to-right and deletes

${var//pattern} finds all the characters in the variable that are pattern-matched from left to right, and deletes

${var/#pattern} finds the character that the first line of a variable is pattern-matched to, and deletes

${var/%pattern} finds the character that the end of a variable is pattern-matched to, and deletes


Character-Case conversions

You can convert the characters in a variable to uppercase and lowercase.

${var^^} converts all lowercase characters in a variable to uppercase

${var,} converts all uppercase characters in a variable to lowercase


# char= "Root:x:0:0:root:/root:/bin/bash"

# echo ${char^^}

Root:x:0:0:root:/root:/bin/bash


Determining variable Assignment values

Determine the variable, if the variable has the value of what to do, there is no value to do what action


${var:-value} Displays the value of the variable if the variable has a value, or if it does not, displays the values character

${var:=value} If the variable has a value, the value of the variable is displayed, and if there is no value the value is assigned to the variable var

and displays the value

${var:+value} In contrast to the-symbol, the var variable has a value that returns value.

${var:?error_info} returns Error_info if Var is empty or not set, otherwise returns the value of Var


[[email protected] ~]# unset Char

[Email protected] ~]# echo $char


[[email protected] ~]# echo ${char:=animal}

Animal

[Email protected] ~]#



Using a configuration file for a script program

1. Define the text file, each line "Key=value"

2. Source this file in the script to




Create temporary File command

Mktemp-create a temporary file or directory

mktemp [OPTION] ... [TEMPLATE]

-D,--directory

Create a directory, not a file

-P DIR,--tmpdir[=dir]

indicates the temporary file directory location


Mktemp/tmp/name_file. Xxxx

The X following the creation of this command will randomly transform one character, so that the created file will not conflict

or repeat causes the file cannot be created



install-copy files and set attributes

Install [OPTION] ... [-T] SOURCE DEST

Install [OPTION] ... SOURCE ... DIRECTORY

Install [OPTION] ...-t DIRECTORY SOURCE ...

Install [OPTION] ...-d DIRECTORY ...


Options

-G Group

-M mode

-O Owner


The install command has the function that the make command does not have, that is, he can specify the copied files or the group of directories created.

permissions, which belong to the master




Exercise: Write a script (copy the command and the library it depends on)

1. Prompt the user to enter an executable command name

2. Get the list of library files to which this command depends

3. Copy the command to the target directory (e.g./mnt/sysroot) under the corresponding path

/bin/bash ==>/mnt/sysroot/bin/bash

/USR/BIN/PASSWD ==>/mnt/sysroot/usr/bin/passwd

4. Copy all the library files that this command relies on to the corresponding path under the target directory

/lib64/ld-linux-x86-64.so.2 ==>/mnt/sysroot/lib64/ld-linux-x86-64.so.2

5. After each copy completes a command, do not exit, but prompt the user to type the new command to be copied, and repeat the completion

The above features until the user enters quit script to quit












Answer: Mean time 3 hours, really slow haha,

If you want to copy and use, pay attention to the layout, there may be a line of content has been split into two lines

#!/bin/bash

#

#Description: This script can copy the commands, which has Gaven,

#and the library which the command depended on.


Maindir= "/mnt/sysroot"

Cmd=notquit


Copycmd () {

cmddir=${cmd%/*}/

[-D $maindir $cmddir] | | MKDIR-PV $maindir $cmddir

[-X $maindir $cmd] && echo "The {${1##*/}} command has a existed in $maindir $cmddir." | | CP--preserve $cmd $maindir $cmddir

}


function Cplib {

For I in $ (ldd $cmd | grep-o "/.*[[:space:]"); Do

[-D $maindir ${i%/*}] | | MKDIR-PV $maindir ${i%/*}

[-e $maindir $i] | | CP--preserve $I $maindir $i

Done

}

while [! $cmd = = "Quit"]; Do

Read-p "Input cmd:" cmd

While [-Z $cmd]; Do

Read-p "Please input something:" cmd

Done

[$cmd = = "Quit"] && break

If $ (which $cmd &>/dev/null); Then

cmd=$ (which $cmd)

Copycmd $cmd

Cplib $cmd

Else

echo "($cmd) is not a Linux ' s command"

Fi

Done


Bash programming arrays and string handling

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.