Linux Learning notes: Bash color display and shell scripting related

Source: Internet
Author: User
Tags define local


Bash's color display rules:

ASCII encoding is set for color:


\033:ctrl Key

[: Control the spacing character between character and color code

0m: command to turn off color properties;

1m: Bold for display text characters

4m: Multibyte underline for text word

5m: Make text characters blink

7m: Exchange the background and foreground color of text characters to display;

8m: Sets the background and foreground colors of the text characters to the same color.


30m-39m: Sets the foreground color of text characters; 38m and 39m temporarily useless

40m-49m: Sets the background color of text characters; 48m and 49m are useless.


A complete program that typically contains four types of files:

Binaries (executables), header and library files, Help files, configuration files;


One of the BASH--CLI (Command line interface)

Bash also belongs to the full application, and there are four types of files:


Bash configuration file:

Three categories:

Profile class:

A configuration file that implements the function initialization for the interactive logon shell process;

BASHRC class

A configuration file that implements the configuration for the start-up of a shell process for non-interactive logons;

Logout class

A configuration file that provides termination and cleanup class functionality for the interactive logon shell process;


The type of shell;

Interactive Login Shell:

1. Enter the account and password directly through a terminal and log in to the open shell process;

2. Use Su-username or su-l username to perform a switch login to open the shell process;


Non-interactive login shell:

1. In the graphical interface, open the shell process of the terminal through the menu or the right-click menu;;

2. Using SU username to perform a switch login open shell process


Bash configuration file:

Profile class:

Global: A configuration file that is valid for all users;

/etc/profile

/etc/profile.d/*.sh


Note: In the Rhel or CentOS series of operating systems, typically, if a profile has a lot of content, the format is complex




User profile: Only the user-specific configuration file;

~/.bash_profile


The profile class configures the role of the file:

1. Used to define the user's environment variables;

2. Used to run scripts or execute commands;


BASHRC class:

Global:

/etc/bashrc

User personal:

~/.bashrc


The BASHRC class configures the role of the file:

1. Used to define local variables;

2. The alias used to define the command;

3. Definition of umask;


Note: Only Superuser root can modify the configuration file of the global class, and ordinary users can only modify the personal profile in their home directory;


The following configuration files are loaded sequentially by the interactive logon shell process;

/etc/profile--/etc/profile.d/*.sh--and ~/.bash_profile--~/.BASHRC--/ETC/BASHRC


The non-interactive login shell process will load the following configuration files in sequence;

~/.BASHRC--/ETC/BASHRC-/etc/profile.d/*.sh


All commands executed at the command line are generally valid only for the current shell life cycle, as long as they do not involve modification of the file, and all settings are invalidated as long as the shell process is complete;


The role of the configuration file: so that we rely on the configuration information can be long-term effective, as long as not modify the contents of the configuration file, each time the shell opened to make the previous configuration to take effect;



A method that allows the newly defined configuration in the configuration file to take effect immediately:

1.source command:

Source/path/to/some_conf_files

. /path/to/some_conf_files


2.exec command:

Exec/path/to/some_conf_files


How the string is handled in the variables stored in bash:

Weak variables:

1. Can be used without prior definition.

2. No hard requirements for variable data type, default is string;


1. String slices:

${#VAR}: Returns the length of the variable VAR of the string type;

${var:offset}: Returns the contents of the string variable VAR after the first offset character, excluding the first offset character, and the value range of offset: 0~$[${#VAR}-1]

${var:offset:number}: Returns the character portion of the string variable VAR starting from the first offset character and the length of number;

${var:-length}: Takes the rightmost length character of the string;


2. Based on the pattern-fetching string:

${var#*pattern}: From the left and then, look for the string stored in the VAR variable, the first pattern-matched character, and remove all characters from the beginning of the string to the pattern-matched character.

${var##*pattern}: From left to right, find all the characters in the string stored by the VAR variable, all of which are pattern-matched, and remove any character from the beginning of the string to the last pattern-matching character.

${var%pattern*}: From right to left, look for the string stored in the VAR variable, the first pattern-matched character, and remove all characters from the end of the string to the pattern-matched character.

${var%%pattern*}: From right to left, look for all characters in the string stored by the VAR variable that match the pattern, removing all characters from the end of the string to the last pattern-matching character.


3. Find a replacement:

${var/pattern/substring}: Find the contents of the match PATTERN in the VAR variable and replace the result with the first match to SUBSTRING.

${var//pattern/substring}: Find the contents of the match PATTERN in the VAR variable and replace all of its matching results with SUBSTRING.


${var/#PATTERN/substring}: Find the content in the VAR variable that matches the PATTERN at the beginning of the line and replace the matching result with SUBSTRING.

${var/%pattern/substring}: Find the contents of the line end matching PATTERN in the VAR variable and replace the matching result with SUBSTRING.


4. Find and Delete:

${var/pattern}: Finds the matching PATTERN in the VAR variable and deletes the first result.

${var//pattern}: Finds the matching PATTERN in the VAR variable and deletes the first result.


${var/#PATTERN}: Find the match PATTERN in the VAR variable and delete the result that matches the beginning of the line.

${var/%pattern}: Finds matching PATTERN content in the VAR variable and deletes the result that matches the end of the line.


5. Case conversion:

${var^^}: Lowercase to uppercase

${var,,}: uppercase to lowercase


6. Variable Assignment:

${var:-value}: If the variable var is empty or not set, return the value of value directly, otherwise return the value of the variable var.

${var:+value}: If the variable VAR is not empty, then return value

${var:=value}: If the variable var is empty or not set, return the value of value directly and assign value to Var, otherwise return the value of VAR of variable


7. Indirect references to variables:

If the value of the first variable is exactly the variable name of the second variable, the method that references the value of the second variable from the first variable is called an indirect variable reference.

Var1=var2

Var2=value

Bash provides two ways to reference indirect variables in a format:

Eval myvar=\$ $VAR 1 ==> \ $VAR 2

myvar=$ (! VAR1)


Array


Variable: memory storage space;

Variables: Only one data can be stored in each variable, and the variable can only be assigned once.


The name of each person in this class is stored in the variable:

1. Disposable Assignment:

Name= "name1 name2 name3 ..."

2. Use multiple variables to assign values, respectively:

Name1=xxx

Name2=ooo

3. Array variables:


Array: A contiguous memory space that holds one or more elements, equivalent to a collection of multiple variables.

Array elements: Any storage unit in the array that holds the data;

Index of the array:

1. Numbers: Indexed arrays (index array)

0,1,2 ...

2. Name (string): Associative array

bash4.0 The above version is supported;


Dense arrays and sparse arrays:

Dense arrays: Index numbers must be contiguous

Sparse arrays: Index numbers can be discontinuous, and bash arrays belong to this class;


Declaring an array:

1.declare command:

Declare-i Name: Declares the name as an integer variable;

Declare-x Name: Declares the name as an environment variable;


Declare-a Name: Declares the name as an indexed array; (if supported)

Declare-a Name: Declares the name as an associative array; (if supported)


2. Declare the array directly:

Assign a value directly to an array:

Array_name= ("Valuel" "value2" "value3" ...) declares a dense array;

Array_name= ([0]= "Valuel" [1]= "value2" [2]= "Value3" ....) declares a sparse array;

3. Create an array by defining the elements of the array:

Array_name[0]=value1

Array_name[1]=value2

Array_name[2]=value3

......


To reference an element in an array:

Methods for referencing variables: ${name}

Methods for referencing array elements: ${array_name[index]}

Note: If index is not given, it represents the first element of the reference array, the element of index=0;

Referencing all elements of an entire array: ${array_name[*]} or ${array_name[@]}

Index of reference array: ${! Array_name[*]} or ${! Array_name[@]}


View the length of the array (number of valid elements in the array)

${#ARRAY_NAME [*]} or ${#ARRAY_NAME [@]}


Array slices:

${array_name:offset}: Displays the index position that includes the offset number and all subsequent elements.

${array_name:offset:number}: Displays the index position that includes the offset number, and the subsequent numbers element;


Append an element to the array:

1. Dense array:

array_name[${#ARRAY_NAME [*]}]=valuen


2. Sparse Arrays:

Array_name[index]=valuen

Note: Index must be numbered for an array element that is not used;


Undo Array:

Unset Array_Name


To delete an element in an array:

Unset Array_name[index]


Random variable: 0-32767

Entropy Pool

/dev/random

/dev/urandom


Bash Script Programming:


Shell script Programming Features:

Over-programming languages

Scripting class Language

Interpreted language


Programming Languages:

Sequential execution structure

Executes all statements (commands) from left to right, from top to bottom;

The body structure of the shell script


Select Execute Hook

According to the logical judgment result of the given condition, then select the statement in a branch to execute;

If: Branch selection criteria, the result of logical judgment;

Case: Branch selection criteria, based on optional values


Loop execution Structure

For a specific operation of a specific statement, repeated 0 times, 1 or more times;

For: Iterates through the specified list;

While: results based on logical judgments

Until: According to the result of logical judgment

Select: The perpetual cycle of death, using a looping mechanism to provide a selection list;



Select the execution structure:

If statement:

If:if order; then command; [elif command; then command;] ... [Else command;] Fi

Executes the command according to the condition.


If statement single branch structure: If the condition is true, then the statement after then is executed, otherwise, no action is taken.

If CONDITION

Then STATEMENT

Fi


if CONDITION; then

STATEMENT1

STATEMENT2

...

Fi


Note: You want to execute the statement after then, provided the condition part is true;


Two-branch structure of the IF statement: if the condition is true, then the command followed by then executes the command after the else;

If Condition;then

STATEMENT

...

Else

STATEMENT

Fi


Multi-branch structure of the IF statement: first determine whether CONDITION1 is true, if true, execute the first then after the statement, otherwise determine whether the second CONDITION2 is true, if true, then judge the second then after the statement .... If all condition are false, then the statement following the else is executed.

if CONDITION1; then

STATEMENT

...

Elif CONDITION2;

STATEMENT

...

Elif CONDITION3;

STATEMENT

...

...

Else

STATEMENT

...

Fi

Recommendation: If multi-branch structure, can not be used.



User interaction for Bash scripting:

Positional parameter variable: $1,$2,$3 ...

Special variables:

$#: Sum of all positional parameters;

$*: A list of all positional parameters given; When using double quotation marks, the entire argument list is treated as a string;;

[Email protected]: A list of all positional parameters given, when using double quotation marks, each parameter exists as a separate string.

$: The path of the script file itself executed


Read command:

Read[-a array] [-D delimiter] [-I buffer literal] [-n read Characters] [-P prompt] [-t timeout] [name ...]

The name is usually the variable name or the array name, and if the name is not written, the system will save read read information in the reply variable;


Shift [N]

Shift position parameters.



Draw flowchart



If statement multi-branch structure:

if CONDITION1; then

STATEMENT

...

Elif CONDITION2;

STATEMENT

...

Elif CONDITION3;

STATEMENT

...

...

Else

STATEMENT

...

Fi



Loop execution Structure:

Repeat a piece of code 0 times, 1 times, or multiple times;

A good cycle structure must include two of the most important links;

Conditions to enter the loop:

Conditions that are satisfied when the cycle begins;

Conditions to exit the loop:

The condition that the end of the cycle satisfies;


Bash script:

For

While

Until

Select


For loop:

1. Traversing the list

for:for variable name in list; Do

Loop Body

Done

Variable name: any of the specified variable names, and the value of the variable is taken from the list and assigned value;

Loop body: Typically a combination of commands or commands that can be used with variable names, and if the loop body does not include a variable name, a dead loop may occur

How the list is generated:

1) Give a direct

2) List of pure integers

SEQ: Output An integer list

seq [First [INCREMENT]] Last

3) curly braces unfold

{first.. Last}

4) return value of the execution result of the command

5) GLOBBING

6) references to certain variables: [email protected], $*



Features of the For loop:

1. There is almost no cycle of death;

2. The entire list needs to be loaded into memory during the execution of the loop, so it may consume too much memory and CPU resources for large lists

2. Control variables

for (expression 1; expression 2; expression 3); Do command; Done


for (expression 1; expression 2; expression 3); Do

Loop body

Done


Expression 1: Assigns the initial value to the variable;

Expression 2: The exit condition of the loop;

Expression 3: Variable value of the law of Change;


Linux Learning notes: Bash color display and shell scripting related

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.