Here's what bash is about, including Bash's color code, Bash's four-class files, how variables are handled in bash, array variables, the shell's procedural programming language, and some simple scripting examples.
One, bash color display rules (color code)
Bash's color code, which is ASCII encoded for color settings. In the color code, the string \033: Represents CTRL. The following functions are implemented for each character of the color code:
[: Control the spacing character between character and color code
0m: command to turn off color properties
1m: Bold for displayed text characters
4m: Multibyte underline for text word
5m: Make text characters blink
7m: Change the background and foreground color, white to black, black to white
8m: Hide characters, set the background and foreground colors of text characters to the same color, same as black or white
30m-39m: Sets the foreground color of text characters, that is, the characters that display what color, 38m and 39m are not used temporarily
40m-49m: Sets the background color of the text character, that is, the background of the black character, the background of what color, 48m and 49m is not used temporarily
Example: multiple composite examples
# echo-e "\033[5;1;31;47mhello world\033[0m" must be added with the-e option, be interpreted; then add [0m exit
II. bash four types of files
A complete program that typically includes four types of files: binaries (executables), header vault files, Help files, and configuration files. Bash is an interface program that is a command-line interface (CLI), so it also includes the four class.
The shell has two types, the shell of the interactive login and the non-interactive login shell, as explained below:
(1), interactive login shell: Enter the account and password directly through a terminal login open shell process; Use Su-username or su-l username to perform a switch login open shell process
(2), non-interactive login shell: In the graphical interface, through the menu or the right-click menu to open the terminal shell process; Use SU username to perform a switch login open shell process
In bash, # File/bin/bash is used to query the file,/usr/include/under the library file,/usr/share/Help file, example: # Ls/usr/share/man/man1
Bash has three types of profiles: (1), Profile class: The configuration file that implements the function initialization for the shell process of the interactive login, (2), The BASHRC class: The configuration file that implements the configuration for the shell process of non-interactive login, (3), Logout class: Provides a configuration file that terminates the cleanup class feature for the interactive logon shell process
1. Profile Category
In the Rhet or CentOS operating system, typically, a configuration file has a lot of content, the format is complex, we will switch it to multiple fragments, the cut out of the pieces of the unified in the "program name. D" file, in such a directory to save the fragment file, Most of them are named with a uniform file suffix name.
The profile category is divided into global and user-specific two types, specifically explained as follows:
Global (Profile): profiles that are in effect for all users, with/etc/profile and/etc/profile.d/*.sh
User Personal (Profile): Only a valid configuration file for a user, with ~/.bash_profile
The profile configuration file has two functions: that is, to define the user's environment variables, to run scripts or execute commands.
2, BASHRC class
BASHRC class is also divided into global and user personal two, the specific explanation is as follows:
Global (BASHRC Class):/ETC/BASHRC
User Personal (BASHRC Class): ~/.BASHRC
The BASHRC class configuration file has three functions: that is, to define local variables; To define aliases for commands; define Umask
Note: Only Superuser root can modify the profile of the global class, whereas a normal user can only modify personal profiles in their home directory
3, Logout class
The order in which the login process loads the configuration files can be as follows:
The following configuration files are loaded sequentially by the interactive logon shell process:/etc/profile--->/etc/profile.d/*.sh---->~/.bash_profile--->~/.BASHRC----- >/etc/bashrc
For non-interactive logon shell processes, the following configuration files are loaded in sequence: ~/.BASHRC----->/ETC/BASHRC---->/etc/profile.d/*.sh
All command operations performed at the command line, as long as no file modifications are involved, are generally valid only for the current shell life cycle, as long as the shell process is complete and all settings are invalidated. The role of the configuration file is as follows: The configuration information that we rely on to survive can be long-term, as long as the content in the configuration file is not modified, each time you open the shell will make the previous configuration effective.
There are two types of the source command and the EXEC command that allow the newly defined configuration in the configuration file to take effect immediately, as explained below:
1. SOURCE command: Runs the contents of the shell in the current command. The following two kinds of specific commands:
Source/path/to/some_conf_files
. /path/to/some_conf_files
2. EXEC command: Replace the shell with the specified command. The specific commands are as follows:
Exec/path/to/some_conf_files
Three, bash in the variable processing mode
A variable is a piece of storage space in memory. The weak variables, which do not need to be defined beforehand, are not required by the variable data type, and the default is the character type.
The 7 types of string content that a variable holds in bash are handled as follows (its value does not change when processed, but only when it is executed):
1. String slicing
${#VAR}: Returns the length of the variable VAR of the string type
${var:offset}: Returns the content after the offset character in the string variable VAR, excluding the offset character, and the value range of offset is: 0-$[$ (#VAR)-1]
${var:offset:number}: Returns the character portion of the string variable VAR starting with the first offset character and a length of numer
${var:-length}: Takes the rightmost length of the string and selects from right to left
2, based on the pattern to take the string
${var#*pattern}: From left to right, find the string stored in the VAR variable, the first pattern-matched character, delete all characters from the beginning of the string to the pattern-matched character (can take the base name)-----left Behind
${var##*pattern}: From left to right, look for all the pattern-matched characters in the string stored in the VAR variable, removing the character from the beginning of the string to the last pattern match
${var%pattern*}: From right to left, look for the string stored in the VAR variable, the first pattern-matched character, delete all characters from the beginning of the string to the pattern-matched character (you can take the directory name)------Leave the front
${var%%pattern*}: From right to left, look for all characters in the string stored by the VAR variable, all of which are pattern-matched, and delete all characters from the beginning of the string to the last pattern-matched character
3. Find and replace
${var/pattern/substring}: Find the contents of the match PATTERN in the VAR variable and change the result of 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 to 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 content of the line end matching PATTERN in the VAR variable and replace the matched result with SUBSTRING
4. Find and delete
${var/pattern}: Find the contents of the match PATTERN in the VAR variable and delete the result that matches the first one
${var//pattern}: Find the match PATTERN in the VAR variable and delete the result that matches it
${var/#PATTERN}: Find the contents of the match PATTERN in the VAR variable and delete the result that matches the beginning of its line
${var/%pattern}: Find the contents of the match PATTERN in the VAR variable and delete the result that matches the end of its line
5. Case conversion of characters
${var^^}: Converts all lowercase letters in the VAR variable to uppercase letters
${var,}: Converts all uppercase letters in the VAR variable to lowercase letters
6. Assigning Values to variables
${var:-value}: If the variable is empty or not set, return the value of value directly, otherwise return the variable VAR
${var:+value}: If the variable is not empty, return the value of Var directly, otherwise return value
${var:=value}: If the variable is empty or not set, return the value of value directly and assign value value to variable Var, otherwise return the value of VAR of variable
7. Indirect references to variables
If the value of the first variable is 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 reference to the variable, also known as an indirect variable reference. Example: Var1=var2 var2=value
Bash provides a way to refer to indirect variables in two formats: (1), eval myvar=\$ $VAR 1 equivalent to Myvar=value, (2), myvar=${! VAR1}
Four, array variables
The variable is in-memory storage space. Variables are characterized by the fact that only one data can be stored in each variable, that is, the variable can only be assigned once, otherwise it is overwritten.
Example: Store Each person's name in the variable, three ways of assignment are as follows:
(1), Disposable assignment: anme= "name1 name2 name3 ..."
(2), using multiple variables to assign values: Name1=little1 name2=little2 name3=little3 ...
(3), using array variables
1. Components of an array
Array variable: A data group of similar attributes that holds contiguous memory space for one or more elements (and, of course, an empty array), which is equivalent to a collection of multiple variables.
Array elements: Any storage unit in the array that holds the data
The index of an array consists of two parts:
(1), Number: Index Array (Index) example 0,1,2,3,4,5,......
(2), Name (string): Associative array (related array); Associative arrays are supported only for versions above bash4.0
2, the classification of the array
Arrays are divided into dense arrays and sparse arrays. Dense arrays, whose index numbers must be contiguous, sparse arrays whose index numbers can be discontinuous, and bash arrays belong to such sparse arrays.
3. Declaring arrays
(1), declare command
Declare-i Name: Declare name as shaping variable
Declare-x Name: Declare name as environment variable
DECLARE-A Name: Declare name as an indexed array (available when versioning is supported)
DECLARE-A Name: Declare name as associative array (available when versioning is supported)
Example: Declare-a name= ("value1" "value2" "value3" ...)
Declare-a name= ([0]= "value1" [1]= "value2" [6]= "Value3" ...)
(2), declaring an array directly
Array_name= ("value1" "value2" "value3" ...) That is, a dense array is declared--Directly array assignment
Array_name= ([0]= "value1" [1]= "value2" [6]= "Value3" ...) That is, declaring a sparse array
(3), an array created to define the elements of an array
Array_name[0]=value1
Array_name[1]=value2
......
4. Refer to the elements in the 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
Index number of all elements referencing the entire array: ${! Array_name[*]} or ${! Array_name[@]}
Referencing all elements of an entire array: ${array_name[*]} or ${array_name[@]}
5. Find the length of the array (number of valid elements in the array)
${#ARRAY_NAME [*]}
${#ARRAY_NAME [@]}
6. Array slicing
${array_name:offset}: Display includes offset example: ${array_name:6}: Skipped 0-5, starting from 6, skipping 6
${array_name:offset:number}: Displays the index position that includes the offset array and the subsequent number elements
Example: ${array_name:6:3}: Skipped 0-5, starting with 6, showing 6, 7, 8, which skipped 6.
7. Append elements to the array:
Dense array Append: array_name[${#ARRAY_NAME [*]}]=valuen
Sparse array Append: Array_name[index]=valuen Note: The index appended by the sparse array must be an indexed number for an array element that is not used
8. Undo array: Usnet Array_Name
9. Delete the elements in the array: usnet Array_name[index]
Random variable: Stochastic number variable, 0-32767 (2^15-1)
Five, Bash script programming
Example 1, write a script: Create a user little, if the user already exists, prompts the user already exists the information, otherwise will create the user
# ID Little &>/dev/null && echo Presence | | Useradd Little
1, Shell script programming features: Procedural programming language, scripting language, interpreted language.
The programming language consists of 3 basic structures, the execution structure, the selection execution structure and the cyclic execution structure, which are explained as follows:
Shun Xiu execution structure: Execute all statements (commands) from left to right, top to bottom, sequential execution structure is the principal structure of shell scripts
Select execution structure: According to the logical judgment result of the given condition according to the optional range of values, then select the statement in a branch to execute. Specifically, if and case two branch structure, that is, if the branch selection criteria, is the result of logical judgment; the branch selection criteria for case is based on optional values.
Loop execution structure: repeats n times for a particular statement. Specifically for, while, until, select, the explanation is as follows:
For: Traversal of the specified list, list must exist beforehand, large scale is not recommended
While: Judging whether the loop is entered according to the result of logical judgment
Until: Determine whether to enter the loop according to the result of logical judgment
Select: a perpetual cycle of death that executes without giving a command exit
2. Select the execution structure:
If statement: If is a shell keyword and does not allow aliases
Format: if command; then command; [elif command; then command] ... [Else command;] Fi
The 2 types of single-branch structure representations of the If statement are as follows:
If CONDITION
Then statement
Fi
If Condition;then
Statement1
Statement2
......
Fi
Note: You want to perform the statements after then, if the condition part is true
Two-branch structure of the IF statement: Executes the command after then if the condition is true, or executes the command following the else
If Condition;then
Statement
......
Else
Statement
......
Fi
Multi-branching structure of the IF statement: first to determine if CCONDITION1 is true, if true, to execute the statement after the first then, otherwise to determine whether CONDITION2 is true, if true, then execute the statement after the 2nd then ...
If Condition1;then
Statement
......
Elif Condition2;then
Statement
......
Elif Condition3;then
Statement
......
Fi
Example 2: Write a script that lists the bash users of the default shell in the system
#!/bin/bash
#
If Grep-q "bash$"; then
grep "bash$" | Cut-d:-f1
Fi
3. User interaction between Bash scripts
The location parameter variables for the bash script are: $, $, $ 、......
The special variables for bash scripts are:
$#: The total number 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 parameters for all locations given, when using double quotation marks, each argument exists as a separate string
$: The path of the script file itself executed
Example 3: Create a user who prompts the user for information that already exists if the user already exists, or creates a user
#!/bin/bash
#
If ID $ &>/dev/null;then
echo "exists"
Else
Useradd $
Fi
Example 4: Write a script, pass the user name parameter to the script, determine whether the parameter quantity is qualified, and determine whether the user exists, if present, display the corresponding information, otherwise create and set the password for it
#!/bin/bash
#
If [$#-ne 1];then
echo "Only one USERNAME can spacified."
Exit 5
Fi
If ID $ &>/dev/null; Then
echo "$ exists already."
Else
Useradd $
echo $ | passwd--stdin $ &>/dev/null
echo "Create $ successfully."
Fi
4. Read command: Read is a built-in command of bash
Format: Read [-a array] [-P prompt] [-t timeout] [name ...]
[name] in read format: typically variable name or array name, if no name is written, the system will save read read information in the reply variable
Example 5:# read-p "Please enter some username:" NAME1 NAME2 NAME3 Enter after output: Please enter some username:little1 little2 little3
Note: Read can enable the user to interact with the shell, and when using the Read command, the time-out is usually specified with the-t option, and once the time-out is defined with the-t option, we must later determine if the given variable is empty, and if it is empty, provide a default value for the variable name
Example 6: Write a script that can add or remove user accounts, use the-a option to complete the Add, use the-D option to complete the delete task
#!/bin/bash
#
If [$#-ne 2]; Then
echo "Usage: $ (basename $)-a Useranme | -D username. "
Exit 5
Fi
if [= = '-a ']; Then
If ID $ &>/dev/null; Then
echo "$ exits already."
Else
Useradd
echo | passwd--stdin &>/dev/null
echo "Create $ successfully."
Fi
Fi
if [= = '-d ']; Then
If ID $ &>/dev/null; Then
Userdel-r
echo "Delete $ finished."
Else
echo "User $ does not exit."
Fi
Fi
Example 7: Determine if the given file size is greater than 100kb, if it is greater than 100kb, it is a large file, otherwise it will show this is a small file
#!/bin/bash
#
filesize=$ (Wc-c < $)
If [$filesize-gt 102400]; Then
echo "Big file."
Else
echo "Small file."
Fi
Example 8: Determine whether a given string is an integer
#!/bin/bash
#
If echo $ | grep "^\<[[:d igit:]]\+\>$" &>/dev/null; Then
echo "is integer."
Else
echo "is not an integer."
Fi
5. Shift command (to complete migration of positional parameters)
Shift format: Shift [n]
Example 9: Extension of Example 6, with shift implementation: Write a script that can add or remove user accounts, use the-a option to complete the add, and complete the delete task with the-D option
#!/bin/bash
#
If [$#-ne 2]; Then
echo "Usage: $ (basename $)-a Useranme | -D username. "
Exit 5
Fi
if [= = '-a ']; Then
Shift
If ID $ &>/dev/null; Then
echo "$ exits already."
Else
Useradd $
echo $ | passwd--stdin $ &>/dev/null
echo "Create $ successfully."
Fi
Fi
if [= = '-d ']; Then
Shift
If ID $ &>/dev/null; Then
Userdel-r $
echo "Delete $ finished."
Else
echo "User $ does not exit."
Fi
Fi
Example 10: Easy Calculator
#!/bin/bash
#
Echo $[$1$2$3]
Reference: #./little.sh 3 + 5 output 8 (3 inputs)
6. Multi-branch structure of the IF statement:
If Condition1;then
Statement
......
Elif Condition2;then
Statement
......
Elif Condition3;then
Statement
......
Else
Statement
......
Fi
Example 11: Write a script that asks: Randomly select a user from the same UID and GID in the/etc/passwd to determine the user's type: UID is 0, that is, Superuser, UID is 1-999, i.e. system user, UID is 1000 +, login user.
#!/bin/bash
#
lines=$ (egrep "\< ([[:d igit:]]+) \>.*\1"/etc/passwd | wc-l)
SEQUENCE=$[${RANDOM}%${LINES}+1]
username=$ (egrep "\< ([[:d igit:]]+) \>.*\1"/etc/passwd | head-n $SEQUENCE | tail-1 | cut-d:-F3)
If [$USERID-eq 0]; Then
echo "$USERNAME is super user."
elif [$USERID-ge 1000]; Then
echo "$USERNAME is login user."
Else
echo "$USERNAME is System user."
Fi
7. Cyclic execution structure
A loop execution structure is a loop of code that executes 0, 1, or more times. A good cycle structure must contain two important links, enter the conditions of the cycle and exit the cycle of conditions, into the cycle of conditions, that is, the conditions to begin the cycle, the condition of exiting the loop, that is, the condition of the end of the loop satisfied
(1), for loop:
Traversal list format for the For loop:
For Var_name in LIST; Do loop body; Done
For Var_name in LIST; Do
Circulation body;
Done
The individual interpretations in the for format are as follows:
Var_name: Any specified variable name, the value of the variable is a value from the list and assigned value
Loop body: A combination of commands or directories that can be used to var_name; if the loop body does not include the variable content var_name, a dead loop may occur
The list is generated in a number of ways, specifically as follows:
1) give directly;
2) List of pure integers: seq: output A list of pure integers seq [first [INCREMENT]] Last example: SQE 1 2 10 (output odd, 2 = increment)
3) Curly braces expand: {first. Last} For example: Echo {1..100}; echo {A.. Z}; echo {A.. Z
4) return value of the execution result of the command
5) GLOBBING
6) references to certain variables: [email protected] $*
Example 12: Write a script that can add or delete one or more user accounts, use the-a option to complete the add, and complete the delete task with the-D option
#!/bin/bash
#
If [$#-lt 2]; Then
echo "Usage: $ (basename $)-a User1 User2 ... | -D User1 User2 ... "
Exit 5
Fi
if [= = '-a ']; Then
Shift
For I in $*; Do
If ID $I &>/dev/null; Then
echo "$I exists already."
Else
Useradd $I
echo $I | passwd--stdin $I &>/dev/null
echo "Create $I successfully."
Fi
Done
Fi
if [= = '-d ']; Then
Shift
For J in $*; Do
If ID $J &>/dev/null; Then
Userdel-r $J
echo "Delte $J finished."
Else
echo "User $J does not exist."
Fi
Done
Fi
8. Advantages and characteristics of the For loop
For loop: Enter loop condition, list of elements can be used, exit loop condition, list is empty, no elements available
For loop features: 1, almost no dead loop, 2, in the process of executing the loop, you need to load the list into memory, so for large lists, may be too much memory and CPU resources
Note: When using a For loop nesting, the outer for loop controls the output of the number of rows, and the inner for Loop, which controls the output of the number of columns
Example 13: Computes 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
For I in $ (seq $INTEGER); Do
# Let sum+= $I
# let sum= $SUM + $I
Sum=$[sum+i]
Done
Echo $SUM
Within 100 can also be: for I in {1..100}; Do-I in {seq $}; Done
Example 14: Write a script that prints the inverted isosceles triangle. Number of stars per line formula: 2*[n-($n-1)]-1; (Total Rows-No. +1)
1 0 9 rows-1 spaces and (total rows-lines) + 1 stars
2 1 7
3 2 5
4 3 3
*5 4 1
#!/bin/bash
#
Linenum=$1
For I in $ (seq $LINENUM); Do
For J in $ (seq $[i-1]); Do
Echo-n ""
Done
For K in $ (seq $[2* (linenum-i) +1]); Do
Echo-n "*"
Done
Echo
Done
Example 15: Print a 99 multiplication table
#!/bin/bash
#
For I in {1..9}; Do
For J in $ (seq $I); Do
Echo-ne "$I * $J =$[i*j]\t"
Done
Echo
Done
1x1=1 1x2=2 1x3=3 ... 1x9=9
2x2=4 2x3=6 ... 2x9=18
...
9x9=81
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: Assigning an initial value to a variable
Expression 2: Exit criteria for loops
Expression 3: Variable Value change law
Example 16:# for ((I=1; i<=100; i++)); do let sum+= $I; Done
#!/bin/bash
for ((I=1; i<=100; i++)); Do
Let sum+= $I
Done
Echo $SUM
bash colors, variables, arrays, related script examples