Linux System Bash (Shell) Basics (4)

Source: Internet
Author: User
Tags arithmetic case statement first string function definition

Today we summarize the basic concepts of bash color, configuration files, variables, arrays and related shell scripting.

One. Bash's color display rules

Yes, it's a color display, which is the ASCLL code for the color of the call settings, but in the color code, the string function is implemented as follows:

\033: Represents the CTRL key;

[: Controls the spacing character between the character and the color code;

0m: Turn off color properties;

1m: Bold display of text characters;

4m: Multibyte underline for text word;

5m: Causes the text character to blink;

7m: Change the background and foreground color, white to black, black to white;

8m: Hide characters, set the background and foreground color of the text characters to the same colors, the same as black or white;


30m-39m set the foreground color of text characters, that is, the font color, 38m and 39m is not used temporarily;

40m-49m: Sets the background color of the text character, that is, what color is behind the background of a black character, 48m and 49m are not used temporarily;

Foreground background color

30m 40m black

31m 41m Red

32m 42m Green

33m 43m Yellow

34m 44m Blue

35m 45m Magenta

36m 46m Cyan Blue

37m 47m White

Cases

Bold display of text characters

[Email protected] wjq]# echo-e "\033[1mhello worl\033[0m"

Hello Worl

Multibyte underline for text word

[Email protected] wjq]# echo-e "\033[4mhello worl\033[0m"

Hello Worl

Bold and set underline at the same time, the use of ";" separated;

[Email protected] wjq]# echo-e "\033[1;4mhello worl\033[0m"

Hello Worl


Two. Configuration files

A complete program typically contains four types of files:

Binary file: executable file;

header files, library files;

Help documentation;

configuration file;

All commands at the command line operation, as long as no design to the file changes are only valid in the current life cycle, when the system is closed, and then turned on is not available, the configuration file is the basic method to achieve permanent display of data, the data changes into the configuration file, when the system restarts can also be repeated calls, If you modify the alias alias into a text document BASHRC the configuration file, BASHRC is a configuration file;

Profiles are divided into private profiles and common profile files

Common configuration file:/etc/bashrc,/etc/profile

Private profile: ~/.bashrc,~/.bash_profile

Note: In general, the definition of variables are first-use, do not need to change the configuration file (declaring the variable in the configuration file may cause a system vulnerability) is not necessary to do not change;

The configuration file is divided into three categories:

Profile class:

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

BASHRC class:

A configuration file that enables the configuration of the feature launch for a non-interactive login shell process;

Logout class:

Provides configuration files for terminating and cleaning class functions for the interactive login shell process;


Interactive login:

1. Open the shell process by entering the account password from a terminal;

2. Open the shell process through su-username;

Non-interactive login:

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

2. Open the shell process through SU username;


Profile class:

/etc/profile

/etc/profile.d/*.sh

Global: The configuration file is modified in the above path, can be changed to all logged users;

Often in the profile file, if there is too much content in a configuration file, the system will cut it into fragments, such as PROFILE.D, which will cut out the fragments

One is stored in the "program name. D" Directory, where all the files about the fragment are named with a uniform filename suffix;

~/.bash_profile

Local: Only for the current home directory Users, change it, do not affect other users;


BASHRC class:

/etc/bashrc

Global: Can define valid command aliases, local variables, and mask code umask for all users of the system;

~/.bashrc

Local: Defines a valid command alias for the current user, local variables, and mask code umask;


Three. Variable Application

1. String slicing

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

${var:offset}: Returns the string after the offset character of the string variable var;

${var:offset:number}: Returns the number character after the first offset character of the string variable var;

Cases

[Email protected] wjq]# var= "Hello World"

[Email protected] wjq]# echo ${#var}

11

Returns a string after the sixth character

[[email protected] wjq]# echo ${var:6}

World

Returns the two string after the sixth character

[[email protected] wjq]# echo ${var:6:2}

Wo

2. Pattern-based string: takes pattern-matching strings according to different methods

${var#*pattern}: In the var string variable, search from left to right for the first character that matches the string pattern, deleting all characters from the beginning to the first match to pattern;


${var##*pattern}: In the var string variable, search from left to right for the last character that matches the string pattern, deleting all characters from the beginning to the last match to pattern;


${var%pattern*}: In the var string variable, search right-to-left for the first match to pattern character, delete all characters from start to right-to-left matching the first pattern;


${var%%pattern*}: In the var string variable, right-to-left searches for the last character that matches the pattern, deleting all characters from the beginning to the right-to-left last match;

Cases

[Email protected] wjq]# VAR=/ETC/PASSWD

[[email protected] wjq]# echo ${var#*p}

asswd

Ii

[Email protected] ~]$ VAR=/ETC/PASSWD

[[email protected] ~]$ echo "${var##*/}"

passwd

[Email protected] ~]$ VAR=/ETC/PASSWD

[[email protected] ~]$ echo "${var%s*}"

/etc/pas

[Email protected] ~]$

[Email protected] ~]$ VAR=/ETC/PASSWD

[[email protected] ~]$ echo "${var%%s*}"

/etc/pa

[Email protected] ~]$


3. Find and Replace: Search for characters that match the pattern in a string in different ways, and replace it with a substring string;

${var/pattern/substring}: In the var string variable, search for the first string matched to pattern, and replace it with a substring string;


${var//pattern/substring}: In the var string variable, search all strings matched to string pattern and replace with substring string;


${var/#pattern/substring}: In the var string variable, search for a string that matches the string pattern at the beginning of the line and replace it with the substring string;


${var/%pattern/substring}: In the var string variable, search for a string that matches the string pattern at the end of the line and replace it with the substring string;


Cases

[Email protected] ~]$ VAR=/ETC/PASSWD

[[email protected] ~]$ echo "${var/e/wu}"

/wutc/passwd

Ii

[Email protected] ~]$ VAR=/ETC/PASSWD

[[email protected] ~]$ echo "${var//s/wu}"

/etc/pawuwuwd

[Email protected] ~]$ VAR=/ETC/PASSWD

[[email protected] ~]$ echo "${var/#\//wu}"

wuetc/passwd

[Email protected] ~]$ VAR=/ETC/PASSWD

[[email protected] ~]$ echo "${var/%d/wu}"

/etc/passwwu


4. Find and Delete: Use different methods to search for matching strings and delete them;

${var/pattern}: In the string variable var, the first match to the pattern string is deleted;


${var//pattern}: In the string variable var, all matching to the pattern string is deleted;


${var/#pattern}: In the string variable var, the string that matches the beginning of the line to pattern is deleted;

${var/%pattern}: In the string variable var, match the end of the line to the string deletion of pattern;


Cases

[Email protected] ~]$ VAR=/ETC/PASSWD

[[email protected] ~]$ echo "${var/p}"

/etc/asswd

Ii

[Email protected] ~]$ VAR=/ETC/PASSWD

[[email protected] ~]$ echo "${var//s}"

/etc/pawd

[[email protected] ~]$ echo "${var/#\/}"

etc/passwd

[[email protected] ~]$ echo "${VAR/%WD}"

/etc/pass


5. Case Conversion of characters:

${var^^}: Converts all lowercase letters in the string var variable to uppercase letters;

${var,}: Converts all uppercase letters in a string var variable to lowercase letters;


Cases

[Email protected] ~]$ VAR=/ETC/PASSWD

[[email protected] ~]$ echo "${var^^}"

/etc/passwd

[Email protected] ~]$



6. Variable Assignment:

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


${var:+value}: If the variable var is not empty, return value, or null to return VAR;


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


Cases

[Email protected] ~]$ var=//

[[email protected] ~]$ echo "${VAR:-QQ}"

//

[Email protected] ~]$ var=

[[email protected] ~]$ echo "${VAR:-QQ}"

Qq


Ii

[Email protected] ~]$ var=

[[email protected] ~]$ echo "${VAR:+QQ}"

[Email protected] ~]$ Var=a

[[email protected] ~]$ echo "${VAR:+QQ}"

Qq


7. Indirect references to variables:

If the value of the first variable is exactly the variable name of the second variable, the method that refers to the value of the second variable from the first variable is called the indirect variable reference;

Var1=var2

Var2=value

Bash provides two types of indirect variable references in the form of:

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

myvar=$ (!VAR1)


Four. Arrays

Array: Equivalent to a set of several variables, storing one or more memory space;

Only one-dimensional arrays are provided in bash, and the array size is not qualified, and the array elements are indexed by subscript 0, which is the index node of the array: 0,1,2 ..., arrays can be assigned with successive index nodes-dense arrays, or they can be assigned with discontinuous index nodes- -Sparse Array.

Array name [subscript]= Value

For example:

$a [0]=beijing

$a [1]=hainan

$a [2]=shanghai


Declaration of the array:

1. Arrays can be assigned individually by the above declaration

2. Assign values directly to an array element:

$a = ("Beijing" "Shanghai" "Tianjin") or $a= ([0]= "Beijing" [1]= "Shanghai" [3]= "Tianjin")

3. Create an array with the DECLARE command:

$declare-a array name

To reference an array element:

1. $name or ${name}, the same as the two, if the variable is not defined by null value substitution;

2. Referencing a fixed array element: ${name[n]} refers to the value of the index node n;

3. Referencing all elements of the entire array: ${name[*]} or ${name[@]}


Cases

[Email protected] ~]$ a[0]=beijing

[[email protected] ~]$ echo "${a[0]}"

Beijing


[[email protected] ~]$ a= ("Wujunqi zhengzhong shaoning")

[[email protected] ~]$ echo "${a[0]} ${a[1]} ${a[2]}"

Wujunqi Zhengzhong shaoning


To view the length of an array:

You can show how many meaningful elements are in this array by ${#name [*]};

Cases

[Email protected] ~]$ a= (Wujunqi zhengzhong shaoning)

[[email protected] ~]$ echo "${#a [*]}"

3


Array slices:

${name:offset}: Displays the index position that includes the offset number and all subsequent elements, removing the offset array element starting from the first one

${name:offset:number}: Displays the index position that includes the offset number, and the numeric element that includes the offset element;

such as ${name:3:2}: Discard 0-2 of the array variable, only take the 3,4 array variable;

Undo Array:

Unset Array_Name


To delete an element in an array:

Unset Array_name[index]


Random variable: Can produce a set of stochastic variables between 0-32767

Cases

[Email protected] ~]$ echo "$RANDOM"

16952

[Email protected] ~]$ echo "$RANDOM"

6653

Five. Bash script programming

There are three types of shell scripting:

Over-programming languages

Scripting Class programming language

Explanatory language

Where the Scripting Class programming language is implemented by invoking external files when implementing the function;

The programming language has three kinds of structure, executes the structure sequentially, chooses the execution structure and the cyclic branch structure;

1. Sequential execution structure:

According to the script commands written by the user, from left to right, from top to bottom in order to execute;

2. Select the execution structure:

For a particular statement, repeat 0 times, one or more times, such as a if,case statement;

If statement:

Single BRANCH statement:

if test condition

Then command

Fi


Two-branch statements:

if test condition

Then command 1

else Command 2

Fi


Multi-branch statement:

if test condition

Then command 1

Elif Test conditions

Then command 2

。。。

Fi

Cases

Calculates the and of all integers within 100;

#!/bin/bash

#

Read-t 5-p "Please input a integer[0]:" Integer

If [-Z $INTEGER]; Then

Integer=0

Fi

if! echo $INTEGER | Grep-q "^\<[[:d igit:]]\+\>$"; Then

echo "You must input an integer."

Exit 5

Fi


Case statement:

The advantage of the case statement is that it saves the resources consumed by the system, as compared to If,else's multi-branch statement, the syntax format is:

Case variable reference in

Mode 1)

Branch 1

;;

Mode 2)

Branch 2

;;

...

*)

Default Branch

;;

Esac

The procedure is to use the value represented by the variable reference to compare with each type of pattern, if the value referenced by the variable is found to be the same as a certain class of pattern, execute the command after the pattern string until the end of two semicolon is encountered;

The pattern of case statements can match the patterns of numbers, strings, wildcard characters, etc.

Attention:

① there can be one or more commands behind each pattern string, and the last command must be ";;" Separated

② pattern strings can be used with wildcard characters;

③ If a pattern string contains multiple schemas, the ' | ' is applied Separated

④ each pattern string should be unique;

⑤ End with keyword ESAC;


3. Circular branching structure

Repeat a piece of code 0 times, 1 or more times; a good loop structure must include two of the most important aspects, namely the condition of entering the loop: the condition that satisfies when the cycle is started;

Conditions to exit the loop:

The condition that the end of the cycle satisfies;

There are three types of statements in the shell that are used for looping, namely for,whie,until,select statements;

For statement:

The For statement is the most commonly used loop structure statement. There are two main ways of using it, one is the value table, the other is the arithmetic expression, the For Loop feature, almost no dead loop, in the process of executing the loop, it is necessary to load the list into memory, so it may consume too much memory and CPU resources for large list;

Value Table mode

Its general expression is

For variable [in value table];d o command table;

The ① value table can be a file regular expression in the form of:

For variable in file regular expression

Do

Command table

Done

Its execution is, the value of the variable in order to take the current directory and the regular expression matches the file name, each value once, enters the loop body executes the command table, until all the filenames are finished;

User interaction for Bash scripting:

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

Special variables:

$#: The total number of all positional parameters;

$*: A list of all positional parameters; When a reference is used, the entire parameter is treated as a string;

[Email protected]: all positional parameter lists; when using "" reference, each parameter exists as a separate string;

$: The path of the executed script file itself;

The ②for loop script can also be the full positional parameter $ #与 $*

For variable in $*

Do

Command

Done

A For loop script can directly use a list of pure integers

{1..100}: Indicates from 1-100, the middle can only be two points;

For i in {1..100}

Do

Command

Done


SEQ: Output An integer list

seq [OPTION] ... First INCREMENT Last

Seq 10: From 1-10

Seq 5 10: From 5-10

For I in $ (seq 10)

Do

Command

Done

Expand on the function of the Read command here

Read command: Reads the data from the keyboard and assigns it to the specified variable;

Read [-a array] [-P prompt] [-t timeout] []

Use the read command to interactively assign a value to a variable, and when entering data, the data is separated by a space or a tab character;

The number of variables is the same as the given number of data, then assign the value

$read x y Z

$today is sunny

$echo $x $y $z

Today is sunny

Ii

The number of variables is less than the number of data, the left-to-right assignment, but the last variable is given to all the remaining number;

The number of variables is more than the number of data, then the corresponding assignment, and no data with the corresponding variable to take empty string;

Cases

The-P option in the script gives the hint, which is equivalent to the Echo

$read-P "Please enter" name

-T option is returned in 5 seconds if no input is entered, the default name is link;

$read-T 5-p "please enter[link]" name | | [-Z $name] && name=link

Arithmetic expression mode:

Its general format is

for (expression 1; expression 2; expression 3)

Do

Command table

Done

Expression 1: Assigns the initial value to the variable;

Expression 2: loop exit condition;

Expression 3: Variable value of the law of Change;

Such as

For ((t=1;i<=100;i++));d o let "sum+=i";d One;echo $sum


While statement:

Format:

①while command; do command; done

②while Condition;do

Loop body

Done

When the condition is true, enter the statement in the loop body, until the condition is false, jump out of the loop;

Example execution while loop when positional parameter exists

While [$]

Do

If [-F $]

Then

echo "This file is a plain text file"

Else

echo "is not a file"

Fi

Done


Until statement:

Format:

①until command; do command; done

②until Condition;do

Loop body

Done

When the condition is false, enters the execution loop body the statement, until the condition is true, jumps out the circulation;


Loop control command:

Continue statement:

Jump out of the current loop statement, back to the beginning of the loop, into the next round of conditions to judge, if the conditions are entered into the next round of circulation;

If you are in a multilayer nested loop, such as:

For

While

For

Continue [3]

Jumps out to the outermost loop, carries out the next round condition judgment of the outermost loop, and continues the loop if it matches;

For example:

For I in 1 2 3

Do

If [$i-eq 2]

Then

Continue

Fi

echo "$i"

Done


Break statement:

The break statement can cause the script to exit from the body of the loop, similar to continue, in the syntax format:

Break [n]

n the default value is 1, that is, jumping out of a layer of loops;

If n=3, it means to jump out of the three-layer loop continuously;

For example

For I in $*

Do

If [$i-eq 5]

Then

Break

Else

echo "$i"

Fi

Done

Exits the current loop when the positional parameter equals 5 o'clock;


Function:

Some functions are packaged together and can be called directly when needed, and the encapsulated functional body is called function;

The function is formally consistent with the shell program, but the shell program can be executed directly, but the statement in the function is to be executed after the function call, and the command in the function is run in the environment of the current shell. The command in the shell program is run in the child shell environment;

A function should be defined before it can be executed, directly used as a normal command, directly using the function name, such as show, without parentheses to invoke, Shell script and function can be passed the parameter, the function of the value of $1,$2 is the function in the call with the argument, you can also use $* or [ e-mail protected] to refer to all positional parameters, you can also use the $ #计算为函数传递的参数个数; this is different from ordinary commands; The life cycle of a function is from the beginning of the call until the return end command is encountered or all the command statements are executed;

Such as

Show Arg1 Arg2

Arg1 and arg2 as arguments to functions;


function definition Format:

Syntax One:

Function name ()

{

Command table

}

Syntax Two:

Function name ()

{

Command table

}

Use the SET command to view all functions in effect in the current shell;

Use the unset command to undo a function that has already been defined;

There are two return values for functions after calling a function:

The return value of the ① function result

such as echo,print and other output results;

② function state return value;

return [0];

The return value of the function cannot be used with the Exit command, n is the exit value when exiting the function, that is, the value of $?, and the exit value is the return value after the last command is executed, when the value is default.


Linux System Bash (Shell) Basics (4)

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.