当前位置:网站首页>Shell concise tutorial
Shell concise tutorial
2022-06-27 13:32:00 【User 3147702】
1. brief introduction
Shell The function of is to explain and execute the user's command , The user enters a command ,shell Just one , This approach becomes interactive , There's another way , That is, the user writes a shell Script , Contains many commands , And then let shell One time execution , This way is called “ Batch processing ”. Usually we are in UNIX Used in shell Namely bash and sh, Of course, there are others shell, stay UNIX It can be used in the environment /etc/shells: valid login shells Command to display all shell, Want to switch , Direct input shell Name is enough .
2. bash start-up
bash The startup script is bash A script that will be executed automatically at startup , Therefore, the user can set some environment variables and alias、umask Put settings, etc. into the startup script , So every time you start shell Will take effect automatically . however , start-up bash Different methods , The steps to execute the startup script are also different .
2.1. Log in as an interaction Shell start-up , Or use —login Parameter startup
Interaction Shell It refers to that the user enters a command at the prompt Shell, Instead of executing scripts shell.
This starts bash The following script will be executed automatically : 1. perform /etc/profil, When each user in the system logs in, it executes , Only administrators can modify 2. Then execute the... Of the current user's home directory in turn ~/.bash_profile、~/.bash_login and ~/.profile Three files ( If it exists ) 3. stay Shell Exit time , Will execute ~/.bash_logout Script ( If it exists )
Usually in ~/.bash_profile There will be the following lines in :
if [ -f ~/.bashrc ]; then
~/.bashrc
fisuch , If ~/.bashrc There is , Will continue to call this script .
2.2. Interactive non login shell start-up
For example, open a terminal window under the graphical interface , Or log in Shell Enter... At the prompt bash command , You get an interactive non - login shell. such shell Automatically execute at startup ~/.bashrc Script . therefore , If you want to make some settings in the startup script , Make it in the graphics terminal window and character terminal Shell It all works in the world , It's best to ~/.bashrc Set in .
If terminal or remote login , So log in Shell Is the parent of all other processes of the user , So the environment variables are logging in Shell It can be automatically brought to other non logins once it is set in the startup script of Shell in , Local variables 、 function 、 alias There is no way to bring the settings to the child Shell in , You need to start non login every time Shell Set it up again , So you need to have a non login Shell Start script for , So generally speaking, in ~/.bash_profile Set environment variables in , stay ~/.bashrc Set local variables in 、 function 、 alias etc. . If your Linux This is not possible with a graphics system , Since login from the window manager of the graphical interface does not generate login Shell, So the environment variable should also be in ~/.bashrc Set in the .
2.3. Non interactive startup
To execute a script fork The one who came out Shell Yes no interactive Shell, The script file executed at startup has environment variables BASH_ENV Definition , It is equivalent to executing the following command :
if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi2.4. With sh Command to start
If the sh Command to start bash,bash Will simulate sh act .
If you log in as an interactive shell start-up , It will be executed in turn : 1. /etc/profile 2. ~/.profile
If as an interactive Shell start-up , Equivalent to execution .
if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fiWith #! /bin/sh This is the case with the initial script , No scripts will run .
3. Shell How to execute commands
3.1. Execute interactive commands
Those who use which The commands that cannot find the location of the program file are shell Built in commands for , These commands are equivalent to Shell A function in the process of , No separate man manual , You can use the following command to view : man bash-builtins. For non built-in commands ,Shell Meeting fork and exec This command , Create a new process , But for built-in commands, it does not , Such as cd、alias、umask、exit、export、shift、if、eval、[、for、while These commands are built-in commands . Although the built-in command does not create a new process , But there will also be return values , It's usually used as well 0 Indicates that the call was successful , This return value is called Exit Status ( Status code ), You can use special variables $? read out .
3.2. Execute the script
shell The script uses # Notation , amount to C In language // notes , however #! It means that the script uses /bin/sh Explain to perform , Does not represent a comment . The following example is a simple shell Script :
#! /bin/sh
cd ..
lsSave the above code in .sh In file , It's a Shell Script . To execute the script, you only need to enter the command :./script.sh, This is a sh ./script.sh Short form of command .
The steps to execute the above script are :
4. Shell Basic syntax
shell Provides a way to communicate with the operating system . This communication is in an interactive way ( Input from the keyboard operates immediately ) Or as a shell Script execution .shell The script is shell And the sequence of operating system commands , It is stored in a file .
5. Variable
General ,Shell Variables consist of all uppercase letters and underscores , There are two types of Shell Variable .
5.1. environment variable
Environment variables can be passed from the parent process to the child process , therefore Shell The environment variables of the process can be changed from the current Shell Process passed to fork Child processes coming out , Use printenv The command can display the current Shell Environment variables for the process .
5.2. The local variable
Only in the present Shell Process variables , use set The command can display the current Shell All variables defined in the process ( Including local variables and environment variables ) And the function .
Here are some common keywords used and displayed by variables :
5.3. set
Show all current variables and functions .
5.4. Definition of variables
Environment variables are concepts that any process has , And the local variable is Shell Unique concepts , stay Shell in , The definition and usage of environment variables and local variables are similar , stay Shell The following format can be used to define or assign a variable in :
VARNAME=valueThere can be no spaces on either side of the equal sign , Otherwise it will be interpreted as a command or a command line parameter .
5.5. export — Export variables as environment variables
After any variable is defined, it only exists in the current Shell process , It's a local variable , use export Command can export local variables as environment variables , Defining and exporting environment variables can also be done in one step .
export VARNAME=valueOf course, it can also be divided into two steps :
VARNAME=value
export VARNAME5.6. unset — Delete variables
Use unset The command can delete environment variables or local variables that have been defined .
unset VARNAME5.7. echo — Display the value of the variable
Use echo The command can display the value of a variable .
Generally for VARNAME Variable , We use ${VARNAME} Indicates his value , Without ambiguity , We can also use VARNAME Indicates his value .
Shell All variables in are strings ,Shell Variables in do not need to be defined before they are used , Use an undefined variable , The value of this variable is an empty string .
6. wildcard — *、?、[]
Shell There are wildcards in , The following table :
shell Wildcard in
wildcard | significance |
|---|---|
* | matching 0 Any character or characters |
? | matching 1 Any character |
[ Several characters ] | Match any character in the formula bracket |
If we can use ls ch0[012].doc Command to find files , If there is ch00.doc and ch02.doc,ls The parameter of will be directly converted to these two file names , Instead of a matching string .
7. Order substitution — ` or $()
By backquotes ( On the keyboard ESC Under the key , The upper left corner of the main keyboard area ·/~) It is also an order ,Shell The command in the backquote will be executed first , Then replace the result to the original position to execute the original command , The following command :
DATE=`date`
echo $DATEThe quotes and $() It's the same :
DATE=$(date)
echo $DATE8. Arithmetic substitution — $(())
Shell Will $(()) Medium Shell The value of a variable is converted into an integer for arithmetic calculation ( In other cases Shell Treat variables as strings , Unable to perform arithmetic calculation )
VAR=45
echo $(($VAR+3))$(()) Can only be carried out in +、-、*、/ and () operation , And can only perform integer operations .
9. Escape character — \
and C The language is the same ,Shell Escape characters are also required in , Such as \ 、\$、\、`、\"
10. character string — ’、"
stay Shell All characters in the middle single quotation mark are considered normal characters , So there is no need to escape characters , If running :
echo '$SHELL'Will be displayed $SHELL.
echo 'ABC\\'Will be displayed ABC\
Double quotation marks also treat strings in them as literals , But back quotes 、$、 Escape characters and so on keep their original meaning . Such as :
echo "$SHELL"Will be displayed /bin/bash.
echo "`date`"Will be displayed Sun Apr 20 11:22:06 CEST 2003.
11. Shell Script Syntax
Shell Script vs Windows/Dos Batch processing is similar under , That is to put all kinds of commands into a file in advance , A program file convenient for one-time execution , It is mainly convenient for administrators to set or manage . But it's better than Windows Batch processing under is more powerful , More efficient than programs edited with other programming programs , Because it has rich grammar , Control can be realized 、 loop 、 Judgment and a series of similar programming language operations .
12. Conditions for testing — test、[]
command test or [] You can test whether a condition is in the city , If the test result is true , It's time to order Exit Status by 0, If the test result is false , The order is Exit Status by 1( And C The opposite is true in language ) because [] Medium [ It's actually an order , What follows is the parameters of this command , So you need to separate them with spaces .
Here's an example :
VAR=2
test $VAR -gt 1
echo $?Show 0.
VAR=2
test $VAR -gt 3
echo $?Show 1.
test It can also be replaced by []:
VAR=2
[ $VAR -gt 3 ]
echo $?Show 1.
12.1. Common test commands
Common test commands
command | significance |
|---|---|
[ -d DIR ] | If DIR Exists and is a directory , It is true |
[ -f FILE ] | If FILE Exists and is a file , It is true |
[ -z STRING ] | If STRING The length is 0, It is true ( If STRING non-existent , Is also true ) |
[ -n STRING ] | If STRING Length not 0, It is true |
[ STRING1 = STRING2 ] | If two strings are exactly the same , It is true |
[ ARG1 OP ARG2 ] | ARG1 And ARG2 When all are integers ,OP take -eq( be equal to ),-ne( It's not equal to ),-lt( Less than ),-le( Less than or equal to ),-gt( Greater than ),-ge( Greater than or equal to ) One of them |
And C Language is similar to , The test conditions can also be compared with 、 or 、 Illogical operation .
Common logical operations
operation | significance |
|---|---|
[ ! EXPR ] | Logical negation |
[ EXPR1 -a EXPR2 ] | Logic and |
[ EXPR1 -o EXPR2 ] | Logic or |
Such as :
VAR=abc
[ -d Desktop -a $VAR = 'abc' ]
echo $?It should be noted that , If in the above example VAR Variables are not predefined , Then it will be expanded to an empty string by the interpreter , The whole command becomes :
[ -d Desktop -a = 'abc' ]therefore , The interpreter will report the corresponding error .
In order to avoid such an accident , A good Shell Programming habits always put variable values in double quotation marks :
VAR=abc
[ -d Desktop -a "$VAR" = 'abc' ]
echo $?such , although VAR Not predefined , But the command was expanded to .
[ -d Desktop -a "" = 'abc' ]13. Branch control — if、then、elif、else、fi
and C Language is similar to , stay Shell Use in if、then、elif、else、fi Several commands implement branch control , for example :
if [ -f ~/.bashrc ]; then
.~/.bashrc
fi13.1. :
: It's a special instruction , be called “ An empty command ”, The order does nothing , however Exit Status It's always true , You can also use /bin/true or /bin/false Gain is always true or false Exit Status.
if :; then echo "always true"; fiIt is the same as the following example :
if /bin/true; then echo "always true"; fi13.2. read
We can also use read The command waits for the user to type a line of string , Save to a Shell variable .
#! /bin/sh
echo "Is it morning? Please answer yes or no."
read YES_OR_NO
if [ "$YES_OR_NO" = "yes" ]; then echo "Good morning!"
elif [ "$YES_OR_NO" = "no" ]; then
echo "Good afternoon!"
else
echo "Sorry, $YES_OR_NO not recognized. Enter yes or no."
exit 1
fi
exit 013.3. &&、||
And C Language is similar to ,Shell Also provide && And ||
test "$VAR" -gt 1 -a "$VAR" -lt 3Equivalent to .
test "$VAR" -gt 1 && test "$VAR" -lt 3because && Short circuit evaluation characteristics of operation , quite a lot Shell Scripts like to be written as :
test "$(whoami)" != 'root' && (echo you are using a nonprivileged account; exit 1)13.4. case、esac
case The order is similar to C Linguistic switch/case sentence ,esac Used to mark case The end of the statement block . Shell Medium case Statements can be used not only to match numbers , It can also be used to match strings and wildcards .
Here's an example , Each matching branch can have several commands , It must end with ;; end .
#! /bin/sh
echo "Is it morning? Please answer yes or no."
read YES_OR_NO
case "$YES_OR_NO" in
yes|y|Yes|YES)
echo "Good Morning!";;
[nN]*)
echo "Good Afternoon!";;
*)
echo "Sorry, $YES_OR_NO not recognized. Enter yes or no."
exit 1;;
esac
exit 014. for、do、done
Shell The script for Loop structure and C The language is very different , It's similar to some programming languages foreach loop . Like the following example :
#! /bin/sh
for FRUIT in apple banana pear; do
echo "I like $FRUIT"
doneIn the example ,FRUIT It's a variable , Let this variable take values as apple、banana、pear Make a cycle ,done Used to mark the end of the loop .
If there is chap0、chap1、chap2 Wait for the documents , The following loop renames them to chap0~ 、 chap1~ 、 chap2~ etc. .
for FILENAME in chap?; do mv $FILENAME $FILENAME~; done15. while、do、done
while Usage and C The language is very similar , For example, the following is a script to verify the password :
#! /bin/sh
echo "Enter password:"
read TRY
while [ "$TRY" != "secret" ]; do
echo "Sorry, try again"
read TRY
doneWe can be like C Control as in language while The number of cycles :
#! /bin/sh
COUNTER=1
while [ "$COUNTER" -lt 10 ]; do
echo "Here we go again"
COUNTER=$(($COUNTER+1))
done16. Some special variables
There are many variables that are Shell Automatically assigned , The following table .
shell Some special variables in
Variable | significance |
|---|---|
$0 | amount to C Language main Functional argv[0] |
$1 、 $2 … | These are called position parameters (Positional Parameter), amount to C Language main Functional argv[1] 、 argv[2] … |
$# | amount to C Language main Functional argc - 1 , Notice the # The following does not indicate comments |
Represents a list of parameters "$1" "$2" … , For example, it can be used in for In the loop in Back . | |
$? | Last order Exit Status |
$$ | At present Shell The process number of |
Parameters $n go by the name of “ Positional arguments ”.
16.1. shift
shift The command can move the position parameter to the left , such as shift 3 Let go 4 become 1,5 become 2, The original 1、2 Will be discarded , and
17. function
Shell There is no return value or parameter list in the function definition in . As shown in the following example :
#! /bin/sh
foo(){ echo "Function foo is called";}
echo "-=start=-"
foo
echo "-=end=-"Notice the left curly bracket in the body of the function { There must be a space or newline between and the following commands , If the last command and the closing curly bracket } On the same line , There must be at the end of the command ; Number . Shell Functions in scripts must be defined first and then called. , Generally, the function definition is written in front of the script , Write function calls and other commands at the end of the script ( similar C In language main function , This is where the script actually starts ).
Shell The fact that a function does not have a parameter list does not mean that it cannot pass parameters , in fact , Functions are like mini scripts , You can pass any parameter when calling a function , The same is used in the function 0 、 1 、 2 And other variables to extract parameters , The position parameter in the function is equivalent to the local variable of the function , Changing these variables does not affect the outside of the function 0 、 1 、 2 Equivariant . You can use... In the function return Command return , If return Followed by a number indicates the function's Exit Status.
#! /bin/sh
is_directory()
{
DIR_NAME=$1
if [ ! -d $DIR_NAME ]; then
return 1
else
return 0
fi
}
for DIR in "[email protected]"; do
if is_directory "$DIR"
then :
else
echo "$DIR doesn't exist. Creating it now..."
mkdir $DIR > /dev/null 2>&1
if [ $? -ne 0 ]; then
echo "Cannot create directory $DIR"
exit 1
fi
fi
done18. Shell Debugging method of script
Shell Provides options for debugging scripts :
- -n — Read the commands in the script but do not execute them , Used to check for syntax errors in scripts
- -v — While executing the script , Print the executed script command to the standard error output
- -x — Provide tracking execution information , Print out each command and result executed in turn
There are three ways to use these options : 1. Provide arguments on the command line $ sh -x ./script.sh 2. Provide parameters at the beginning of the script #! /bin/sh -x 3. Use... In the script set Command to enable or disable parameters
#! /bin/sh
if [ -z "$1" ]; then
set -x
echo "ERROR: Insufficient Args."
exit 1
set +x
fi19. Example — multiplication table
#
# file: nine.sh
# author: Longquan resident
# date: 2013-05-06 22:58
#
VARI=1
while [ "$VARI" -lt 10 ]; do
VARJ=1
while [ "$VARJ" -lt "$VARI" ]; do
echo -n " "
VARJ=$(($VARJ+1))
done
VARJ="$VARI"
while [ "$VARJ" -lt 10 ]; do
VARM=$(($VARI*$VARJ))
if [ "$VARM" -lt 10 ]; then
echo -n " "
fi
echo -n "$VARM "
VARJ=$(($VARJ+1))
done
echo ""
VARI=$(($VARI+1))
done边栏推荐
- Pre training weekly issue 51: reconstruction pre training, zero sample automatic fine tuning, one click call opt
- PLM还能怎么用?
- jvm 性能调优、监控工具 -- jps、jstack、jmap、jhat、jstat、hprof
- Istio微服务治理网格流量管理核心资源控制器详解
- 思考的角度的差异
- 硬件开发笔记(七): 硬件开发基本流程,制作一个USB转RS232的模块(六):创建0603封装并关联原理图元器件
- Infiltration learning diary day20
- Hue new account error reporting solution
- Postman如何设置成中文?(汉化)
- Tiktok practice ~ public / private short video interchange
猜你喜欢
随机推荐
Deeply convinced plan X - system foundation summary
再懂已是曲中人
Yuweng information, a well-known information security manufacturer, joined the dragon lizard community to build an open source ecosystem
Hardware development notes (VII): basic process of hardware development, making a USB to RS232 module (VI): creating 0603 package and associating principle graphic devices
基于STM32设计的蓝牙健康管理设备
防火墙基础之华为华三防火墙web页面登录
IJCAI 2022 | greatly improve the effect of zero sample learning method with one line of code. Nanjing Institute of Technology & Oxford proposed the plug and play classifier module
Cesium realizes satellite orbit detour
OpenHGNN发布0.3版本
Details of istio micro service governance grid traffic management core resource controller
高效率取幂运算
Quick news: Huawei launched the Hongmeng developer competition; Tencent conference released the "Wanshi Ruyi" plan
Openhgnn releases version 0.3
每日刷題記錄 (六)
dynamic programming
[tcaplusdb knowledge base] Introduction to tcaplusdb tcapulogmgr tool (I)
A pang's operation record
关于接口测试自动化的总结与思考
深入理解位运算
What else can PLM do?









