当前位置:网站首页>Shell script
Shell script
2022-07-05 08:16:00 【chen_ bx】
Shell Script
Preface
Notes of this article refer to Qianfeng education
b Stop video :Linux A full set of video tutorials for advanced programming ( Easy to understand )(1P-17P)
shell grammar
shell Definition and execution of script
The definition begins with :#!/bin/bash
#! Used to declare what the script is made of shell explain , Otherwise use the default shellSingle "#" The number represents the current line of the comment
perform :
chmod + x test.sh ./test.sh Execute after adding executable permission
bash test.sh Directly specify the use of bash explain test.sh
. test.sh(source test.sh) With the current shell Read interpretation test.sh
The first method requires modifying the executable permissions
The second and third do not needThe three ways of executing scripts are different :
./ and bash The execution process is basically the same , The latter clearly specifies bash The interpreter executes the script , Script #! The specified interpreter does not work . The former first detects #!, Use #! designated shell, If you don't use the default shell
use ./ and bash To execute will start a new... In the background shell To execute the script
use . Executing the script will not start a new shell, Directly from the current shell To explain the execution script .
Example
demo1.sh Code
#!/bin/bash
# #! Used to specify the current script file shell Interpreter type , If you don't write , Use the default shell
#shell The script is shell An ordered collection of commands , The code is made up of commands
ls
pwd
echo "hello"
Running results
Shell Variable
Custom variable
shell There is no data type in No, int char…, direct Variable =value
Such as :i = 50
Reference variables
$ Variable name
Such as :i=$num Put variables num The value of is paid to the variable i
Show variable
Use echo The command can display the value of a single variable
Such as :echo $num
Clear variables
Use unset Command to clear variables
Such as :unset varname
Example 1
demo2.sh Code
#!/bin/bash
num=50
i=$num
echo $num
echo $i
unset num
echo "***********delete************"
echo $num
Running results
The following error is reported ( Command not found ) as a result of
num=50
i=$num
Spaces appear on both sides of the equal sign between variables and values
shell Remember not to add spaces during script assignment
Other uses of variables :
read string( Type on scanf)
Enter a string variable from the keyboard string
readonly var=100
Define a read-only variable , Can only be initialized at definition time , It can't be changed in the future , Cannot be cleared .
export var=300
Use export Variable of description , Will be exported as environment variables , Other shell All can use
Be careful : You must use source 2_var.sh It will take effect
matters needing attention
- Variable names can only contain English letters and underscores , Cannot start with a number
1_num=10 error
num_1=20 correct - The equal sign cannot be directly followed by a space character , If the variable itself contains spaces , Then the whole string should be in double quotation marks 、 Or enclosed in single quotation marks ; Special characters in double quotation marks can retain variable characteristics , However, special characters in single quotation marks are only general characters .
name=aa bb // error
name="aa bb" // correct
echo "$name is me" // Output :aa bb is me
echo '$name is me' // Output :$name is me
environment variable
shell At the beginning of execution, some variables related to the working environment of the system have been defined , We are shell Can be used directly in $name quote
Definition :
Generally in ~/.bashrc or /etc/profile In file ( Script automatically called by the system ) Use export Set up , Allow users to change later
VARNAME=value
export VARNAME
Traditionally , All environment variables are capitalized
Show environment variables
Use env Command to view all environment variables .
Clear environment variables
Use unset Command to clear environment variables
Common environment variables :
HOME: The full pathname used to save the registration Directory .
PATH: Used to save colon separated directory pathnames ,shell Will press PATH Search these directories in the order given in the variable , The first executable found that matches the command name will be executed .
PATH=$HOME/bin:/bin:/usr/bin;export PATH
HOSTNAME: Host name
SHELL: default shell Command parser
LOGNAME: This variable holds the login name
PWD: Absolute pathname of the current working directory
......
Environment variables set under the terminal , Only temporarily valid , If you open another terminal or restart it , The environment variable will disappear . If you want to set permanently saved environment variables , Can be found in ~/.bashrc or /etc/profile In file Add
VARNAME=value
export VARNAME
Example 2
demo3.sh Code
#!/bin/bash
echo "You are welcome to use bash"
echo "Current work dirctory is $PWD"
echo "the host name is $HOSTNAME"
echo "your home dir $HOME"
echo "Your shell is $SHELL"
Running results
Preset variables
$#: Pass to shell Number of script parameters
$*: Pass to shell Contents of script parameters
$1、$2、$3、...、$9: Parameters passed to the script when it runs , Space off
$?: The state returned after command execution
"$?" Used to check whether the last command is executed correctly ( stay Linux in , The exit status of the command is 0 Indicates that the command is executed correctly , Anything that is not 0 Value indicates an error in the command )
$0: The name of the currently executing process
$$: The process number of the current process
"$$" The most common use of variables is as the name of temporary files to ensure that temporary files are not repeated
Example
demo4.sh
#!/bin/bash
echo "your shell script name is $0"
echo "the params of your input is $*"
echo "the num of your input params is $#"
echo "the params is $1 $2 $3 $4"
ls
echo "the cmd state is $?"
cd /root
echo "the cmd state is $?"
echo "process id is $$"
Running results
Special usage of script variables :"" `` ’ \ () {}
“”( Double quotes ): The contained variables will be interpreted
‘’( Single quotation marks ): The included variables will be interpreted as strings
``( Number keys 1 The back quote on the left ): The contents in the back quotation marks are used as system commands , And execute its contents , You can replace the output with a variable equivalent to $()
```powershell $ echo "today is `date` "
today is 2012 year 07 month 29 Sunday, Sunday 12:55:21 CST
\ Escape character :
Same as c Language \n \t \r \a etc. echo The command needs to add -e escape
( Command sequence ):
Yuko shell To complete , Does not affect the present shell The variables in the
{
Command sequence }:
At present shell In the implementation of , Will affect the current variable
Example
demo5.sh Code
#!/bin/bash
name=teacher
string1="good moring $name"
string2='good moring $name'
echo $string1
echo $string2
echo "today is `date` "
echo 'today is `date` '
echo -e "this \n is\ta\ntest"
( name=student;echo "1 $name" )
echo 1:$name
{
name=student; echo "2 $name"; }
echo 2:$name
Running results
Conditional test statements
Writing shell Script time , The problem we often encounter is to judge whether the strings are equal , You may also need to check the file status or enter
Conduct digital test , Only after these tests are completed can we do the next step
test command : Used to test string 、 File status and numbers
test There are two formats for commands :
test condition or [ condition ]
When using square brackets , Pay attention to adding spaces on both sides of the condition
shell The condition test in the script is as follows :
File test 、 String test 、 Digital test 、 Composite test
Test statements are generally used in conjunction with the conditional statements described later
File test
By file type
-e file name Does the file exist
-s file name Whether it is not empty
-b file name Block device file
-c file name Character device file
-d file name Directory file
-f file name Ordinary documents
-L file name Soft link file
-S file name Socket file
-p file name Pipeline files
According to file permissions
-r file name Can be read
-w file name Can write
-x file name Executable
Comparison between two files
file 1 -nt file 2 file 1 Whether the modification time of the file is longer than 2 new
file 1 -ot file 2 file 1 Whether the modification time of the file is longer than 2 used
file 1 -ef file 2 Two files inode Whether the node number is the same , Used to determine whether it is a hard link
Example
demo6.sh Code
$? Return execution result 0 To be right Not 0 For a mistake
#! /bin/bash
echo "please input a filename >>> "
read FILE
test -e $FILE
echo " There is ?$?"
test -s $FILE
echo " Non empty ?$?"
[ -r $FILE ]
echo " Can be read ?$?"
[ -w $FILE ]
echo " Can write ?$?"
[ -x $FILE ]
echo " Executable ?$?"
test -b $FILE
echo " Block device file ?$?"
test -c $FILE
echo " Character device file ?$?"
test -d $FILE
echo " Directory file ?$?"
test -f $FILE
echo " Ordinary documents ?$?"
test -L $FILE
echo " Soft link file ?$?"
test -S $FILE
echo " Socket file ?$?"
test -p $FILE
echo " Pipeline files ?$?"
Running results
String test
s1 = s2 Test whether the contents of two strings are exactly the same
s1 != s2 Test whether the contents of two strings are different
-z s1 test s1 Is the length of the string 0
-n s1 test s1 Whether the length of the string is not 0
Digital test
a -eq b test a And b Whether it is equal or not
a -ne b test a And b Is it unequal
a -gt b test a Is it greater than b
a -ge b test a Greater than or equal to b
a -lt b test a Is less than b
a -le b test a Less than or equal to b
Composite test
The first form : Command execution control
&&:
command1 && command2
&& Left command (command1) Successful implementation ( Return 0)shell To perform && The order on the right
(command2)
||
command1 || command2
|| The order on the left (command1) Not implemented successfully ( That is, return non 0)shell To perform || The order on the right
(command2)
The second form : Multiple conditional decision
Control statement
if sentence
Format 1 :
if [ Conditions 1 ]; then
Execute the first procedure
else
Execute the second procedure
fi
Format two :
if [ Conditions 1 ]; then
Execute the first procedure
elif [ Conditions 2 ];then
Execute the second procedure
else
Execute the procedure in the third paragraph
fi
case sentence
case $ Variable name in
“ The first variable content ”)
Program segment 1
;;
“ The second variable content ”)
Segment II
;;
*)
Other program segments
exit 1
esac
for sentence
Form 1 :
for (( Initial value ; Limit value ; Perform steps ))
do
Procedures section
done
Form 2 :
for var in con1 con2 con3 ...
do
Procedures section
done
On the first cycle ,$var The content is con1
On the second cycle ,$var The content is con2
On the third cycle ,$var The content is con3
...
When in After all the following values are assigned and the command is executed , The loop ends
while sentence
while [ condition ]
do
Procedures section
done
When condition Enter when it is established while loop , until condition Exit the cycle only when it is not established
until sentence
until [ condition ]
do
Procedures section
done
In this way while On the contrary , When condition Exit the loop when established , Otherwise continue the cycle .
break、continue
break
break The command allows you to jump out of the loop .
break Usually exit the loop or... After some processing case sentence
continue
continue The order is similar to break command
There is only one important difference , It won't jump out of the loop , Just skip this loop step
function
Some script segments repeat each other , If you can write a code block only once and reference it anywhere, it will improve the reusability of the code .
shell Allows a set of commands or statements to form a usable block , These blocks are called shell function .
Function definition and call
Define two forms of functions :
Format 1 :
Function name ()
{
command ...
}
Format two :
function Function name ()
{
command ...
}
The format of the calling function is :
Function name param1 param2……
Function arguments
Using parameters is the same as using special variables in general scripts
$1,$2 …$9 equally
Function return value
Function can be used return End in advance and bring back the return value
return Returns... From a function , Use the last status command to determine the return value .
return 0 No error returned
return 1 Error returned
边栏推荐
- Network communication process
- Hardware 1 -- relationship between gain and magnification
- [cloud native | learn kubernetes from scratch] III. kubernetes cluster management tool kubectl
- 1-stm32 operation environment construction
- Detailed summary of FIO test hard disk performance parameters and examples (with source code)
- C, Numerical Recipes in C, solution of linear algebraic equations, LU decomposition source program
- Sql Server的存储过程详解
- List of linked lists
- 【云原生 | 从零开始学Kubernetes】三、Kubernetes集群管理工具kubectl
- Process communication mode between different hosts -- socket
猜你喜欢
Semiconductor devices (III) FET
Several important parameters of LDO circuit design and type selection
OC and OD gate circuit
Halcon's practice based on shape template matching [2]
Measurement fitting based on Halcon learning [II] meaure_ pin. Hdev routine
Matlab2018b problem solving when installing embedded coder support package for stmicroelectronic
Development tools -- gcc compiler usage
[tutorial 19 of trio basic from introduction to proficiency] detailed introduction of trio as a slave station connecting to the third-party bus (anybus PROFIBUS DP...)
Several implementation schemes of anti reverse connection protection of positive and negative poles of power supply!
STM32 single chip microcomputer -- volatile keyword
随机推荐
What are the test items of power battery ul2580
Live555 push RTSP audio and video stream summary (I) cross compilation
Various types of questions judged by prime numbers within 100 (C language)
Charge pump boost principle - this article will give you a simple understanding
MySQL MHA high availability cluster
Let's briefly talk about the chips commonly used in mobile phones - OVP chips
Measurement fitting based on Halcon learning [i] fuse Hdev routine
Live555 push RTSP audio and video stream summary (III) flower screen problem caused by pushing H264 real-time stream
Fundamentals of C language
QEMU demo makefile analysis
STM32 tutorial triple ADC interleaved sampling
Shape template matching based on Halcon learning [v] find_ cocoa_ packages_ max_ deformation. Hdev routine
List of linked lists
C WinForm [exit application] - practice 3
STM32 single chip microcomputer - external interrupt
Network port usage
[trio basic tutorial 18 from introduction to proficiency] trio motion controller UDP fast exchange data communication
go依赖注入--google开源库wire
【论文阅读】2022年最新迁移学习综述笔注(Transferability in Deep Learning: A Survey)
Volatile of C language