当前位置:网站首页>Shell programming specifications and variables
Shell programming specifications and variables
2022-07-27 17:04:00 【Aka · Brooklyn Fairy】
Catalog
3,shell Script application scenarios
3、 ... and , Pipe operator operation
1, Interactive hardware devices
5、 ... and , Classification of variables
1, Classification of variables
6、 ... and ,read Command to get input
7、 ... and , environment variable
8、 ... and , A read-only variable
1,shell Script Overview
1,shell The role of
linux In the system shell It's a special application , It lies between the operating system kernel and the user , Acting as a “ command interpreter ” Role . Be responsible for accepting the operation instructions input by the user and explaining , Pass the required operations to the kernel for execution , And output the result .
common shell There are many interpreter programs , Use different shell when , Its internal instructions , There are some differences in command line prompt and so on . adopt /etc/shells File understand what the current system supports shell Types of scripts .

2,shell The concept of script
- Save the commands to be executed in order to a text file
- Give the file executable permissions
- It can combine all kinds of shell Control statements to perform more complex operations
3,shell Script application scenarios
- Repetitive operations
- Interactive tasks
- Batch transactions
- Service running status monitoring
- Scheduled task execution
Two ,,shell Script execution
1, Method 1 : Command to specify the path , It is required that the document must have x jurisdiction
chmod +x /root/first.sh
Specify the absolute path :/root/first.sh
Specify the relative path :./first.sh
[[email protected] opt]# ./nxx.sh
-bash: ./nxx.sh: Not enough permissions
[[email protected] opt]# chmod +x nxx.sh
[[email protected] opt]# ./nxx.sh
Please enter who is a stupid dog :^C
3, Method 2 : Appoint shell To explain the script , It is not required that the document must have x jurisdiction
sh Script path :sh first..sh
source Script path : .first.sh perhaps source first.sh: perhaps bash first.sh
[[email protected] opt]# chmod -x nxx.sh
[[email protected] opt]# ./nxx.sh
-bash: ./nxx.sh: Not enough permissions
[[email protected] opt]# . nxx.sh
Please enter who is a stupid dog :
[[email protected] opt]# source nxx.sh
Please enter who is a stupid dog :
[[email protected] opt]#
[[email protected] opt]# bash nxx.sh
Please enter who is a stupid dog :
[[email protected] opt]#
3、 ... and , Pipe operator operation
The pipe symbol "|" The command output on the left , As input to the command on the right ( Deal with people ), Multiple pipes can be used in the same command line .
stay shell Script , Pipeline operation is usually used to filter the required customs information .
Example
[[email protected] opt]# netstat -natp |wc
15 110 1468
[[email protected] opt]# netstat -natp |wc -l
15
[[email protected] opt]#
Example 2, combination awk Print using spaces for segmentation , Intercept the status of the running socket
[[email protected] opt]# netstat -natp |awk '{print $6}'
established)
Foreign
LISTEN
LISTEN
LISTEN
LISTEN
LISTEN
LISTEN
ESTABLISHED
LISTEN
LISTEN
LISTEN
LISTEN
LISTEN
LISTEN
[[email protected] opt]#
Four , Redirect
1, Interactive hardware devices
| type | Device file | Document description number | Default device |
| The standard input | /dev/stdin | 0 | keyboard |
| standard output | /dev/stdout | 1 | Monitor |
| Standard error output | /dev/stderr | 2 | Monitor ,2, |
2, Redirection operation
| type | The operator | purpose |
| Redirect input | < | Read data from the specified file |
| Redirect output | > | Put the standard output result , preservation , To the specified file |
| >> | Append the output result to the end of the specified file | |
| Standard error output | 2> | Put the error message preservation To the specified file , And cover the original content |
| 2>> | Put the error message preservation To the specified file , Don't cover the original content | |
| Mixed output | &> | Standard output , Standard errors are saved to the same file |
| 2>&1 | Redirect standard error output to standard output |
example 1 ">" ">>"
[[email protected] opt]# echo "zzzzz" > z.txt
[[email protected] opt]# cat z.txt
zzzzz
[[email protected] opt]# echo "pppppp" >> z.txt
[[email protected] opt]# cat z.txt
zzzzz
pppppp
[[email protected] opt]# echo "dfwfwf" > z.txt
[[email protected] opt]# cat z.txt
dfwfwf
[[email protected] opt]#
> Indicates coverage
>> Indicates append example 2 "<"
[[email protected] opt]# passwd --stdin jack < z.txt
Change user jack Password .
passwd: All authentication tokens have been successfully updated .
[[email protected] opt]#
example 3, Standard error output
[[email protected] opt]# dauhfidauhfa 2> z.txt
[[email protected] opt]# cat z.txt
bash: dauhfidauhfa: Command not found ...
[[email protected] opt]# dddddddddfwefc 2>> z.txt
[[email protected] opt]# cat z.txt
bash: dauhfidauhfa: Command not found ...
bash: dddddddddfwefc: Command not found ...
One represents coverage
One means to append
example 4, Mixed output
[[email protected] opt]# cat /etc/passwd &> /dev/null
Standard output , Standard errors are guaranteed in the same file
[[email protected] opt]# cat /saada/daada > z.txt 2>&1
[[email protected] opt]# cat z.txt
cat: /saada/daada: There is no file or directory
[[email protected] opt]#
Redirect standard error output to standard output 5、 ... and , Classification of variables
1, Classification of variables
- It is used to store specific parameters that the system and users need to use
- environment variable : System maintenance , Application settings working environment
- Positional variable : Pass parameters to the script through the command line
- Custom variable : Defined by the user , Modify and use
- Predefined variables :bash A class of variables built into , Cannot be modified directly
2, Define a new variable
Format : Variable name = A variable's value
Variable naming rule : Start with a letter or underline , Case sensitive
[[email protected] opt]# zz=shagou
[[email protected] opt]# bb=caiji
[[email protected] opt]# echo $zz
shagou
[[email protected] opt]# echo $bb
caiji
[[email protected] opt]#
3, Custom variable
Bash The variable operation in is relatively simple , Unlike other high-level programming languages (( Such as c/C++、Java etc. ) So complicated . When defining a new variable , In general, you don't need
Make a statement in advance , Instead, specify the variable name directly and assign it to the initial value ( Content ) that will do
■ Format : Variable name = A variable's value
■ Variable name : A place where data is temporarily stored
A variable's value : Temporary changeable data
■ There is no space on either side of the equal sign . Variable names should start with letters or underscores , Do not include special characters in the name ( Such as +、 One 、*、/、.、 ?、8、&、# etc. )
■ use echo View and reference the values of variables
By adding a leading symbol before the variable name "$”, You can reference the value of a variable , Use echo Command can view variables , Can be in one echo View multiple variable values at the same time in the command
example 1
[[email protected] opt]# unset zz
[[email protected] opt]# unset bb
[[email protected] opt]# zz=aaa
[[email protected] opt]# bb=cxk
[[email protected] opt]# echo $zz$bb
aaacxk
[[email protected] opt]#
When variable names are easily confused with other characters immediately following them , Need to add “{}” Cover up , Otherwise, the correct variable name cannot be determined , For undefined variables , Will display as empty .
example 2,
[[email protected] opt]# unset zz
[[email protected] opt]# unset bb
[[email protected] opt]# zz=aaa
[[email protected] opt]# bb=cxk
[[email protected] opt]# echo $zz$bb
aaacxk
[[email protected] opt]# echo ${zz} ${bb}
aaa cxk
[[email protected] opt]#
Use quotation marks when assigning values
Double quotes : Allowed to pass through $ The symbol references other variable values
Single quotation marks : Do not reference other variable values ,$ Treat as normal characters
Apostrophe : Command substitution , Extract the output of the command after execution .`..` and $(..) The same effect
Apostrophe
[[email protected] opt]# vim zz.sh
[[email protected] opt]# cat zz.sh
#!/bin/bash
let i+=10
echo "$i"
[[email protected] opt]# bash zz.sh
10
[[email protected] opt]# num =`bash zz.sh`
bash: num: Command not found ...
[[email protected] opt]# num=`bash zz.sh`
[[email protected] opt]# echo "$num"
10
[[email protected] opt]#
**
Extract the output result after the command is executed through the apostrophe
Backhand cannot be nested
6、 ... and ,read Command to get input
Purpose : Let users themselves , Assign a value to a variable , flexible
grammar read [ Options ] Variable name
Common options
| Options | paraphrase |
| -p | Define information to prompt users |
| -n | Define the number of characters ( Limit the length of variable values ) |
| -s | No display ( Don't show user input ) |
| -t | Define timeout , The default unit is seconds ( Limit the timeout of user input variable value ) |
example 1,/ Waiting for user input , Assign the entered value to test Variable
[[email protected] opt]# read cxk
123321
[[email protected] opt]# echo $cxk
123321
[[email protected] opt]#
Assign value to cxk
$cxk You can get the assignment example 2, Generally speaking, in order to make the interface of interactive operation more friendly , Improve ease of use , read
Commands can be combined with "-p" Option to set the prompt message , In order to inform the user what content to enter and other related matters
#!/bin/bash
read -p " Who is a stupid dog : " num
echo "${num}" It's a stupid dog
~
~
**
[[email protected] opt]# bash cxx.sh
Who is a stupid dog : cxk
cxk It's a stupid dog
[[email protected] o
Variable action range
By default , The newly defined variable is only in the current shell Effective in the environment , So it's called a local variable , When entering a subroutine or a new subroutine shell Environmental time , Local variables will no longer be used
It can be done by internal command export Exports the specified variable as a global variable , Make user-defined variables in all sub shell Can continue to be used in the environment .
Format 1:export Variable name
Format 2:export Variable name = A variable's value
[[email protected] ~]# nxx=cxk
[[email protected] ~]# echo $nxx
cxk Define a variable
[[email protected] ~]# bash]\
> ^C
[[email protected] ~]# ^C
[[email protected] ~]# bash
[[email protected] ~]# bash Load new environment
[[email protected] ~]# echo $nxx This environment variable cannot be found
[[email protected] ~]# exit
exit
[[email protected] ~]# exit
exit
[[email protected] ~]# export nxx use export Add it to the global variable
[[email protected] ~]# bash
[[email protected] ~]# bash Loading environment
[[email protected] ~]# echo $nxx Sure echo To this variable
cxk
[[email protected] ~]#
The operation of integer variables
| expression | give an example |
| $(()) | echo $((9+9)) |
| $[] | echo $[15-9] |
expr | expr 10/5 |
| let | i=1;let i+=10 be equal to let i=i+10 |
Example
[[email protected] ~]# echo $((18+25))
43
[[email protected] ~]# echo $[2*4]
8
*
[[email protected] ~]# expr 4 \* 8
32
[[email protected] ~]# i=4
[[email protected] ~]# a=3
[[email protected] ~]# let $i \* $a
bash: let: *: Grammar mistakes : Expecting operands ( The error symbol is "*")
[[email protected] ~]# expr $i \* $a
12
[[email protected] ~]# let i+=10
[[email protected] ~]# echo $i
14
[[email protected] ~]#
[[email protected] ~]# let a=a+11
[[email protected] ~]# echo $a
14
i++ amount to i=$[$i+1]
i-- amount to i=$[$i-1]
i+=10 amount to i=$[$i+10]7、 ... and , environment variable
- Use env The command can view the environment variables of the current working environment
- Variable user Represents the user name ,home Indicates the user's add directory ,lang Represents the language and character set ,pwd Indicates the current working directory , Variable path Represents the default search path for executable programs .

8、 ... and , A read-only variable
Used when the variable value cannot be modified
[[email protected] ~]# cxk=shagou
[[email protected] ~]# readonly cxk Set to read-only variable
[[email protected] ~]# cxk=caiji Variables cannot be reassigned
bash: cxk: A read-only variable
[[email protected] ~]# unset cxk
bash: unset: cxk: Can't reset : read-only variable Read only variables cannot be deleted , Restart and disappear .
[[email protected] ~]#
🦼🦼**********Nine , Positional variable
- When executing command operation , The first character represents the command name or script program name , The rest of the characters indicate that they are assigned to the position variable once in order from left to right .
- $n:n Is a number ,$0 For the order itself ,1~9 Represents the first to ninth parameters , More than ten parameters need to be represented by braces , For example, the tenth parameter is ${10}.


Ten , Custom variable
| Built in commands | meaning |
==$?== | The status returned after the last command is executed ; The status value is 0 Indicates normal execution ,== Not 0== Indicates execution exception or error |
| $0 | The name of the program or script currently executing |
| ==$#== | Of the parameters followed by the script == Number == |
| ==$*== | After the script == All the parameters ==, Parameters are output as a whole , Each variable parameter is separated by a space |
| [email protected]== | After the script == All the parameters ==, The parameters are independent , It's all output |
| ==$1~$9== | After the script == Positional arguments ==,$1 It means the first one 1 Position parameters , By analogy |
| ${10}~${n} | Extended location parameters , The first 10 Position variables must use {} Enclosed in braces (2 Add more than one digit ) |
| ==$$== | The process number of the current process , Such as echo $$ |
| $! | The last process number running in the background ( Current terminal |
| !$ | Call... In the last command history == Parameters == |

result

Further connection $* and [email protected] The difference between


Learn more $?
For the status code returned by the previous command .
[[email protected] ~]# bash weizhi.sh A B C D E
A
B
C
D
E
___________________________________
A B C D E
[[email protected] ~]# echo $? The previous command is correct , return 0
0
[[email protected] ~]# bash weizhi.shssss
bash: weizhi.shssss: There is no file or directory
[[email protected] ~]# echo $?
127 The command of the previous day reported an error , Display the error return value
[[email protected] ~]#
边栏推荐
猜你喜欢

Natural sorting: comparable interface, customized sorting: the difference between comparator interface

Unity 入门

Apache

牛客题目——二叉搜索树与双向链表

C语言之数据的储存

Shardingsphere-proxy-5.0.0 distributed snowflake ID generation (III)

meta-data 占位符的引用
Interpretation of C basic syntax: summarize some commonly used but easily confused functions (i++ and ++i) in the program (bit field)

JSP El expression, JSTL tag

Flex弹性盒布局2
随机推荐
Process control statement
Niuke topic -- judge whether it is a complete binary tree or a balanced binary tree
Complete steps of JDBC program implementation
JDBC连接数据库
LNMP环境--部署wordpress
Servlet用Cookie实现用户上次登录时间
JSP El expression, JSTL tag
实测:云RDS MySQL性能是自建的1.6倍
第7天总结&作业
Interpretation of C basic syntax: summarize some commonly used but easily confused functions (i++ and ++i) in the program (bit field)
String numeric type converted to thousands
Passive income: return to the original and safe two ways to earn
Opencv (III) -- image segmentation
京东张政:内容理解在广告场景下的实践和探索
VS2019 C语言如何同时运行多个项目,如何在一个项目中添加多个包含main函数的源文件并分别调试运行
牛客题目——判断是不是完全二叉树、平衡二叉树
What is JSP?
数据采集之:巧用布隆过滤器提取数据摘要
JDBC程序实现完整步骤
Advanced pointer of C language