Array of shell scripts and Yum "Down"

Source: Internet
Author: User
Tags define local prepare rand

Array of shell scripts and Yum "Down"


Array

Variables: Storing the memory space of a single element

Array: A contiguous memory space that stores multiple elements, equivalent to a collection of multiple variables.


Array name and Index

Index: Numbering starting from 0, which is a numeric index

Note: Indexes can support the use of custom formats, not just numeric formats, which are associated with indexes, which are supported after the bash4.0 version. The array of Bash supports sparse format (index discontinuity)

Declaring an array: declare-a Array_Name

Declare-a array_name: Associative array


Array Assignment

Assignment of array elements:

(1) Assign only one element at a time;

Array_name[index]=value

weekdays[0]= "Sunday"

Weekdays[4]= "Thursday"

(2) Assign all elements at once:

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

(3) Assign only specific elements:

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

(4) Assignment of interactive array value pairs

Read-a ARRAY


referencing arrays

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

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

The length of the array (the number of elements in the array):

${#ARRAY_NAME [*]}

${#ARRAY_NAME [@]}


Example: Generate 10 random numbers to save in an array and find their maximum and minimum values


#!/bin/bash

Declare-a Rand

Declare-i max=0

Declare–i min=32767


For i in {0..9}; Do

rand[$i]= $RANDOM

echo ${rand[$i]}

[${rand[$i]}-gt $max] && max=${rand[$i]}

[${rand[$i]}-lt $min] && min=${rand[$i]}



Done


echo "Max: $max Min: $min"



Write a script that defines an array in which the elements in the array are all files ending in. Log in the/var/log directory, and the sum of the number of rows in the file to be labeled even


#!/bin/bash

# declare-a Files

Files= (/var/log/*.log)

Declare-i lines=0


For I in $ (seq 0 $[${#files [*]}-1]); Do


If [$[$i%2]-eq 0];then

Let lines+=$ (Wc-l ${files[$i]} | cut-d "-F1)



Fi

Done

echo "Lines: $lines."



Array Data processing

To reference an element in an array:

All elements:

${array[@]}, ${array[*]}

Array slices:

${array[@]:offset:number}

Offset

Number of elements to skip

Number

Number of elements to remove

All elements after the offset is taken

${array[@]:offset}

Append an element to the array:

array[${#ARRAY [*]}]

Delete an element in an array: causes sparse formatting

Unset Array[index]

Associative arrays:

Declare-a Array_Name

Note: You must first declare, then call Array_name= ([idx_name1]= ' val1 ' [idx_name2]= ' val2 ' ...)



String processing

Bash's string processing tool:

String slices:

${#var}:

Returns the length of the string variable var

${var:offset}:

Returns the string variable var starting with the character specifier (excluding the first offset character) from the first, and the value of offset between 0 and ${#var}-1 (bash4.2, negative values allowed)

${var:offset:number}:

Returns the string variable var, starting with the character specifier (excluding the first offset character) from the first, the part of the length number

${var:-lengh}:

Take the rightmost few characters of a string

Note: You must have a blank character after a colon

${var:offset:-lengh}:

Skips the offset character from the leftmost side until the rightmost lengh character of the string is taken




To take a substring based on a pattern:


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

Features: From left to right, find the var variable stored in the string, the first occurrence of Word, delete all characters from the beginning of the string to the first occurrence of Word characters

${var##*word}: Ibid., the difference is that everything is removed from the beginning of the string to the last character specified by word


Example:


File= "Var/log/messages"

${file#*/}: Log/messages

${file##*/}: Messages



${var%word*}: Where word can be any of the specified characters;

Function: From right to left, find the var variable stored in the string, the first occurrence of word, delete the last character of the string to the left to the first occurrence of all characters between word characters;


Example file= "/var/log/messages"

${file%/*}:/var/log

${var%%word*}: Ditto, except delete all characters from the rightmost character of the string to the left to the last occurrence of word characters;


Example: url=http://www.magedu.com:80

${url##*:} 80

${url%%:*} http




Find Replacements:

${var/pattern/substi}: Finds the string that is represented by Var, the first time it is matched to by pattern, and replaces it with Substi

${var//pattern/substi}: Find the string represented by Var, all the strings that can be matched to by pattern, to substi replace the ${var/#pattern/substi}: Find the string represented by Var, The string to be matched by pattern at the beginning of the line, replaced by Substi ${var/%pattern/substi}: Finds the string represented by Var, the string to which the end of the row is matched by pattern, and replaces it with Substi



Find and Delete:

${var/pattern}: Find the string represented by Var, delete the string that was first matched by pattern

${var//pattern}: All

${var/#pattern}: Beginning of the line

${var/%pattern}: End of line

Character-Case Conversions:

${var^^}: Converts all lowercase letters in VAR to uppercase

${var,}: Converts all uppercase letters in VAR to lowercase




Assigning values to variables

${var:-value}: Return value if Var is empty or not set, otherwise the value of VAR is returned ${var:+value}: Returns value if Var is not empty, otherwise returns a null value ${var:=value}: If Var is empty or not set, Then return value and assign value to Var; otherwise, the value of VAR is returned ${var:?error_info}: If Var is empty or not set, then the Error_info is printed at the current terminal; otherwise, the value of VAR is returned

Use a configuration file for a script to implement variable assignments

(1) Define a text file, each line defines "Name=value"

(2) Source This file in the script to



Shell variables are generally untyped, but the bash shell provides declare and typeset two commands to specify the type of the variable, and two commands are equivalent


Declare [options] variable name

-r Set Variable to read-only property

-I defines a variable as an integral number

-a defines a variable as an array

-a defines a variable as an associative array

-F Displays all function names and their contents defined before this script

-F displays only all function names defined before this script

-X declares a variable as an environment variable


-L

Convert a variable value to a lowercase letter

Declare–l Var=upper-u

Convert variable value to uppercase

Declare–u Var=lower


Indirect variable Reference

If the value of the first variable is the name of the second variable, referring to the value of the second variable from the first variable is called an indirect variable reference


Variable1=variable2

Variable2=value

The value of Variable1 is Variable2, and variable2 is the variable name,

Value of variable2, indirect variable reference refers to the behavior of getting the value of a variable by variable1


The bash shell provides two formats for implementing indirect variable references

Eval tempvar=\$ $variable 1

Tempvar=${!variable1}


Example:


[Email protected] ~]# N=name

[Email protected] ~]# name=45

[Email protected] ~]# n1=${! N

[Email protected] ~]# echo $N 1 45

[Email protected] ~]# eval n2=\$ $A

[[email protected] ~]# echo $45




eval command

The eval command will first scan the command line for all permutations before executing the command. This command applies to variables that scan for a time that does not function. This command scans the variable two times


Example:


[Email protected] ~]# Cmd=whoami

[Email protected] ~]# echo $CMD whoami

[Email protected] ~]# eval $CMD


Create a temporary file

Mktemp command: Create a temporary file to avoid conflicts

mktemp [OPTION] ... [TEMPLATE] TEMPLATE:filename.XXX x must appear at least three


OPTION:

-D: Create a temp directory

-P DIR or--tmpdir=dir: Indicates the location of the directory where the temporary files are stored

Example:

#mktemp/tmp/test.xxx

#tmpdir = ' mktemp–d/tmp/testdir.xxx '

#mktemp--tmpdir=/testdir test. Xxxxxx


Install copy files

Install Command:


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

Install [OPTION] ... SOURCE ... Directory install [OPTION] ...-t directory SOURCE ...

Install [OPTION] ...-d DIRECTORY ... Create an empty directory


Options:

-M MODE, default 755-o OWNER

-G GROUP



Example:

Install-m 700-o wang-g Admins file1 file2

Install–m–d/testdir/installdir



How bash expands command-line precedence

Dividing the command line into a single command word


Expand aliases

Expand the Declaration of curly braces ({})

Expand Tilde Declaration (~)

command to replace $ () and ')

Divide the command line into command words again

Expand File Wildcard (* 、?、 [ABC], etc.)

Prepare for i/0 redirection (<, >)

Run command




Bash's configuration file



In terms of effective scope, there are two categories:

Global configuration:

/etc/profile

/etc/profile.d/*.sh

/etc/bashrc

Personal configuration:

~/.bash_profile

~/.bashrc



Shell Login Two ways

Interactive login:

(1) Directly through the terminal input account password login;

(2) User execution order using "su-username" switch:/etc/profile---/etc/profile.d/*.sh----~/.bash_profile------~/.BASHRC---E Tc/bashrc


Non-interactive logon:

(1) Su UserName

(2) The terminal opened under the graphical interface

(3) Execute script Execution order: ~/.BASHRC---/ETC/BASHRC-/etc/profile.d/*.sh



Profile class

By function, there are two kinds: Profiile class and BASHRC class


Profile class: Provides configuration for the interactive logon shell global:/etc/profile,/etc/profile.d/*.sh Personal: ~/.bash_profile function: (1) to define environment variables (2) run a command or script


BASHRC class: Provides configuration for non-interactive and interactive logon shells global:/ETC/BASHRC Personal: ~/.BASHRC

Function: (1) Define command aliases and functions (2) Define local variables



Editing the configuration file takes effect


There are two ways to do this when you modify the profile and BASHRC files:

1 restarting the shell process

2. or source


Cases:. ~/.bashrc


Bash quits task

Save in ~/.bash_logout file (user)

Run when you exit the login shell

For

Create an automatic backup

Clear Temporary files



Yum's repository pointing and compiling installation



Yum command-Line options:

--nogpgcheck: No GPG check

-Y: Auto Answer "yes"

-Q: Silent mode

--disablerepo=repoidglob: Temporarily disables the repo specified here

--enablerepo=repoidglob: Temporarily enable the repo specified here

--noplugins: Disable all plugins



How to use a disc as a local yum repository:

(1) Mount the disc to a directory such as/media/cdrom # Mount/dev/cdrom/media/cdrom

(2) Creating a configuration file

[CentOS7]

Name=

Baseurl=

gpgcheck=

Enabled=


Package compilation

Package Compilation Installation:

APPLICATION-VERSION-RELEASE.SRC.RPM---after installation, use the Rpmbuild command to make the RPM package in binary format before installing

Source code---preprocessing----compile--------

Source Code organization format:

Multiple files: Between the code in the file, there is likely to be a cross-file dependency

C, C++:make (project manager, configure---makefile.in-Makefile)


Java:maven



C Code compilation installation three steps:

1,./configure:

(1) Pass the parameter through the option, specify enable feature, install path, etc., refer to User's designation and makefile.in file generation makefile when executing

(2) Check the dependent external environment, such as dependent packages

2. Make: Build the application according to the makefile file

3. Make install: Copy files to the appropriate path

Development tools:

AUTOCONF: Generate Configure Script

Automake: Generate makefile.in

Note: See Install,readme before installing



Prepare: Provide development tools and development environment development tools: make, GCC and other development environments: Development Library, header file glibc: standard library Implementation: providing development components through "package groups"

CentOS 6:

Development Tools

Server Platform Development

CentOS 7:

Development Tools Development and Creative Workstati



First Step: Configure script

Options: Specify the installation location, specify the enabled features

--help: Gets the category of option options it supports:

Installation path settings:--prefix=/path: Specify the default installation location, default is/usr/local/--sysconfdir=/path: Profile Installation location System types: cross-compilation supported



Optional Features: Optional features--disable-feature--enable-feature[=arg]

Optional Packages: Optional package,--with-package[=arg], dependency package--without-package, disabling dependencies

Step Two: Make

Step Three: Make install


Post-installation configuration:

(1) The binary program directory is imported into the PATH environment variable; edit file/etc/profile.d/name.sh export Path=/path/to/bin: $PATH

(2) Import library file path edit/etc/ld.so.conf.d/name.conf add a new library file in the same directory as this file

To have the system regenerate the cache: Ldconfig [-v]

(3) The import header file is implemented in a link-based manner: LN-SV

(4) Import Help manual edit/etc/man.config|man_db.conf file add a Manpath














Array of shell scripts and Yum "Down"

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.