shell script under linux (basic concept)
Document Reprint: https://www.cnblogs.com/yinheyi/p/6648242.html
I just write it down as a note. If it infringes, please leave a message and delete it immediately.
First shell script:
#!/bin/bash echo "Hello, world!"
Variable:
Define variables:
country="China"
Number=100
be careful:
1. There must be no space between variable name and equal sign;
2. The first character must be a letter (A-Z, A-Z).
3. There can be no space in the middle. You can use underscore ().
4. Punctuation cannot be used.
5. You cannot use the keywords in bash (you can use the help command to view the reserved keywords).
Use variables:
Just add the dollar sign $in front of a defined variable. In addition, the {} of the variable is optional. Its purpose is to help the interpreter identify the boundary of the variable
country="China" echo $country echo ${country} echo "I love my ${country}abcd!"
#This needs to have {};
Redefining variables: simply assign values to variables as they were defined:
country="China"
country="ribenguizi"
Read only variable: you can use the readonly command to define a variable as a read-only variable.
readonly country="China"
#Or
country="China"
readonly country
Delete variable: use the unset command to delete variables, but read-only variables cannot be deleted. Usage:
unset variable_name
Variable type
When you run the shell, there are three variables at the same time:
- local variable
Local variables are defined in scripts or commands and are only valid in the current shell instance. Programs started by other shells cannot access local variables. - environment variable
All programs, including those started by the shell, can access environment variables. Some programs need environment variables to ensure their normal operation. Shell scripts can also define environment variables when necessary. - shell variable
Shell variables are special variables set by the shell program. Some of the shell variables are environment variables and some are local variables. These variables ensure the normal operation of the shell
Special variables:
The difference between * and @ is: * and @ represent all parameters passed to a function or script. When they are not contained in double quotation marks ("), all parameters are output in the form of" 1 "," 2 "..." n ". However, when they are contained in double quotation marks ("), "*" will output all parameters as a whole in the form of "12... N"; "@" will separate each parameter and output all parameters in the form of "1", "2"... "$n".
$? You can get the exit status of the previous command. The so-called exit status is the return result after the execution of the previous command. The exit status is a number. Generally, most commands will return 0 if they are executed successfully and 1 if they fail.
echo "-- \$* demonstration ---" for i in "$*"; do echo $i done echo "-- \$@ demonstration ---" for i in "$@"; do echo $i done
Execute the script, and the output results are as follows:
$ chmod +x test.sh $ ./test.sh 1 2 3 -- $* demonstration --- 1 2 3 -- $@ demonstration --- 1 2 3
Substitution in Shell
Escape character:
Escape characters that can be used in echo are:
Use the – e option of echo command to prohibit escape, and it is not escaped by default; Use the – n option to disable the insertion of line breaks; Escape characters can be replaced using the – e option of the echo command.
In addition, note that after my experiment, I get:
echo "\\" #Get\ echo -e "\\" #Get\ echo "\\\\" #Get\ echo -e "\\" #Get\
Command substitution:
It means that we assign the output of a command to a variable by enclosing the command in backquotes (below Esc) For example:
directory=`pwd` echo $directory
Variable substitution:
The value of a variable can be changed according to its state (empty, defined, etc.)
Shell operator
Arithmetic operator:
Native bash does not support simple mathematical operations, but can be implemented by other commands, such as awk and expr Expr is used below; Expr is an expression calculation tool, which can be used to evaluate expressions;
For example:
a=10 b=20 expr $a + $b expr $a - $b expr $a \* $b expr $a / $b expr $a % $b a=$b
be careful:
- The symbol in expr is:*
- There should be a space between the expression and operator in expr, otherwise an error will occur;
- In [a==b] and [a!=b], brackets are also required between square brackets and variables and between variables and operators, otherwise it is wrong. (personally tested)
Relational operators:
Only numbers are supported, not strings, unless the value of the string is a number. Common are:
Note: don't forget the space;
Boolean operator:
String operator:
File test operator:
Detect various properties of Unix files.
String in Shell
Restrictions on single quotation marks:
Any character in the single quotation mark will be output as is, and the variable in the single quotation mark string is invalid;
A single quotation mark cannot appear in a single quotation mark string (nor after using an escape character for a single quotation mark).
Advantages of double quotation marks:
You can have variables in double quotes
Escape characters can appear in double quotation marks
Splice string:
country="China" echo "hello, $country"
#You can
echo "hello, "$country" "
Get string length:
string="abcd" echo ${#string} #Output 4
Extract substring:
string="alibaba is a great company" echo ${string:1:4} #Output liba
Find substring:
string="alibaba is a great company" echo `expr index "$string" is`
String of processing route:
For example, when a path is / home / Xiaoming / 1 Txt, how to its path (without file) and how to get its file name??
To get the file name, use the bashname command:
basename /home/yin/1.txt -> 1.txt basename -a /home/yin/1.txt /home/zhai/2.sh -> 1.txt 2.sh basename -s .txt /home/yin/1.txt -> 1 basename /home/yin/1.txt .txt -> 1
Get the path name (without file name) and use the dirname command:
Parameters: no parameters;
example:
dirname /usr/bin/ -> /usr dirname dir1/str dir2/str -> dir1 dir2 dirname stdio.h -> .
Shell array:
bash supports one-dimensional arrays, not multidimensional arrays. Its subscripts are numbered from 0 Obtain array elements with subscript [n];
Define array:
In the shell, the array is represented by parentheses, and the elements are separated by spaces. For example:
array_name=(value0 value1 value2 value3)
Each component of the array can also be defined separately. Continuous subscripts can not be used, and the range of subscripts is not limited. For example:
array_name[0]=value0 array_name[1]=value1 array_name[2]=value2
Read array: read the element of a subscript. The general format is:
${array_name[index]}
Read all elements of the array, using @ or*
${array_name[*]} ${array_name[@]}
Get array information: get the number of array elements:
length=${#array_name[@]} #or length=${#array_name[*]}
Get the subscript of the array:
length=${!array_name[@]} #or length=${!array_name[*]}
Get the length of a single element of the array:
lengthn=${#array_name[n]}
printf function:
It is similar to printf in c language, but there are also differences. The differences are listed below:
The printf command does not need parentheses
Format string can have no quotation marks, but it is better to add single quotation marks and double quotation marks.
When the parameters are more than the format controller (%), the format string can be reused and all parameters can be converted.
arguments are separated by spaces without commas.
The following is an example:
Conditional statements in Shell
if statement
include: 1. if [ expression ] then sentence fi 2. if [ expression ] then sentence else sentence fi 3. if [ expression] then sentence elif[ expression ] then sentence elif[ expression ] then Statement fi a=10 b=20 if [ $a == $b ] then echo "a is equal to b" else echo "a is not equal to b" fi
In addition, if... else statements can also be written on one line and run in the form of commands, such as:
if test $[2*3] -eq $[1+5]; then echo 'The two numbers are equal!'; fi;
The test command is used to check whether a condition is true, similar to square brackets ([]).
case... esac statement
Case... esac, similar to switch... Case statements in other languages, is a multi branch selection structure. The format of the case statement is as follows:
case value in Mode 1) command1 command2 command3 ;; Mode 2) command1 command2 command3 ;; *) command1 command2 command3 ;; esac
Of which, 1 The first mock exam must be in, and each mode must end with the right bracket. Values can be variables or constants. After matching, the first mock exam is executed until all values are in accordance with a certain mode. Similar to break in other languages, it means to jump to the end of the whole case statement. 2. If there is no matching pattern, use the asterisk * to capture the value, and then execute the following commands.
shell loop statement
for loop
The general format is:
for variable in list do command1 command2 ... commandN done
Note: a list is a sequence of values (numbers, strings, etc.) separated by spaces. Each cycle assigns the next value in the list to a variable. For example:
Output the numbers of the current list in sequence:
for loop in 1 2 3 4 5 do echo "The value is: $loop" done
Display the main directory to Files beginning with bash:
#!/bin/bash for FILE in $HOME/.bash* do echo $FILE done
while Loop
The general format is:
while command do Statement(s) to be executed if command is true done
For example:
COUNTER=0 while [ $COUNTER -lt 5 ] do COUNTER='expr $COUNTER+1' echo $COUNTER done
until loop
The until loop executes a series of commands until the condition is true. The until loop is handled in the opposite way to the while loop. Common formats are:
until command
do
Statement(s) to be executed until command is true
done
command is generally a conditional expression. If the return value is false, continue to execute the statements in the loop body, otherwise jump out of the loop.
Similarly, use break and continue in a loop to jump out of the loop. In addition, the break command can be followed by an integer to indicate which layer of loop to jump out of.
Shell function
Shell functions must be defined before use. The definitions are as follows:,
function_name () { list of commands [ return value ] }
You can also add the function keyword:
function function_name () { list of commands [ return value ] }
be careful:
- To call a function, you only need to give the function name without parentheses.
- Function return value, you can explicitly add a return statement; If not, the result of the last command will be used as the return value.
- The return value of Shell function can only be an integer, which is generally used to indicate whether the function is executed successfully, 0 indicates success, and other values indicate failure.
- The parameters of the function can be obtained by $n For example:
Copy code
funWithParam(){ echo "The value of the first parameter is $1 !" echo "The value of the second parameter is $2 !" echo "The value of the tenth parameter is ${10} !" echo "The value of the eleventh parameter is ${11} !" echo "The amount of the parameters is $# !" # Number of parameters echo "The string of the parameters is $* !" # All parameters passed to the function }
Execution results:
funWithParam 1 2 3 4 5 6 7 8 9 34 73
Copy code
5. Like deleting variables, you can also use the unset command to delete functions, but add f option, as follows:
unset .f function_name
The shell file contains:
The Shell can also contain external scripts to merge the contents of external scripts into the current script. use:
. filename
#Or
source filename
- The effects of the two methods are the same. For simplicity, the point number (.) is generally used, But note the dot (.) There is a space between and file name.
- The included script does not need execution permission.