当前位置:网站首页>Basic usage of shell script
Basic usage of shell script
2022-07-02 01:04:00 【Yizhi_】
List of articles
This article is adapted from https://www.runoob.com/linux/linux-shell.html
Although the tutorial has been well written , But if you don't copy it yourself, it's like you didn't learn . Or are you used to sorting things into your own order , This is convenient for later search and use .
in addition , On this basis, I will add my own examples and details .
Basics
Interpreter
$ which bash
/bin/bash
$ which sh
/bin/sh
Extension
It can be .sh, It can also be .shell
The extension does not affect script execution , See the name and know the meaning
function shell
The way 1: As an executable
chmod +x test.sh
./test.sh
The first line must be correct , Such as #!/bin/bash, So that the system can find the correct interpreter .
add ./ Represents finding... In the current directory test.sh This script ;
If directly executed /test.sh, Will go to PATH In looking for ( There is no the ).
The way 2: As interpreter parameters
/bin/sh test.sh
/bin/php test.php
Scripts that run this way , You don't need to specify interpreter information on the first line , It's no use writing .
notes
- With # The first line is the comment , Will be ignored by the interpreter .
#--------------------------------------------
# This is a comment
# author: Novice tutorial
# site:www.runoob.com
# slogan: It's not just technology that you learn , Is the dream !
#--------------------------------------------
##### User configuration area Start #####
#
#
# Here you can add script description information
#
#
##### User configuration area end #####
:<<EOF The comment ... The comment ... The comment ... EOF
# EOF You can also use other symbols :
:<<' The comment ... The comment ... The comment ... '
:<<!
The comment ...
The comment ...
The comment ...
!
characteristic
sh and bash Some features compared with other programming languages :
- Function can only return strings , Cannot return array ;
- Object oriented... Is not supported ;
- interpreted ;
Variable
Definition
a="abc"
- Definition time , Variable name without dollar sign ($,PHP Variable needs in language )
- There can be no spaces between variable names and equal signs
- The second assignment , No need to add $, Only when calling
assignment
The above definition uses Direct copy , You can also assign values to variables with statements
# take /etc The file names in the following directory are looped out .
for file in `ls /etc`
for file in $(ls /etc)
Call variables
Use a defined variable , To prefix the variable name with a dollar sign
a="abc"
echo $a
echo ${a}
{}
Curly brackets are optional , Add it or not , Plus for Help interpreter Identify the boundaries of variables
Curly brackets are recommended for all variables
A read-only variable readonly
readonly Commands can define variables as read-only variables , The value of a read-only variable cannot be changed
#!/bin/bash
myUrl="https://www.google.com"
readonly myUrl
myUrl="https://www.runoob.com" # Will report a mistake
Delete variables
unset variable_name
- Variable cannot be used again after being deleted .
- unset Command cannot delete read-only variables .
Variable type
function shell when , There will be three variables at the same time :
- local variable
- environment variable
- shell Variable
character string
name='Alice'
# String concatenation
str1='hello, '$name' !'
str2='hello, ${name} !'
str3="Hello, \"$name\"!"
str4="hello, ${name} !"
echo $str1 $str2 $str3 $str4
About Quotes
- Strings can be in single quotes , You can also use double quotes , You can also use no quotes .
- In single quotation marks , Any character will be output as it is , The variables are invalid ;
- A single quotation mark cannot appear in a single quotation mark string , You can't escape a single quotation mark ; But in pairs , Use as string concatenation .
- You can have variables in double quotes
- Escape characters can appear in double quotes
String manipulation
# Get string length
string="abcd"
echo ${
#string} # Output 4
# Extract substring ; The index value of the first character is 0.
echo ${string:1:3} # Output bcd
# Find substrings ; Use backquotes instead of single quotes
echo `expr index "$string" b` # Output 1
echo `expr index "$string" cd` # Output 2
Array
- bash Supports one dimensional array ( Multidimensional arrays are not supported ), And there's no limit to the size of the array .
- Use parentheses to indicate , Element use " Space " Symbol split
- The subscript of the element is 0 Start
Definition
stay Shell in , Use parentheses to represent arrays , For array elements " Space " Symbol split . The general form is :
# Array name =( value 1 value 2 ... value n)
# Such as
array_name=(value0 value1 value2 value3)
# or
array_name=(
value0
value1
value2
value3
)
# Define each component of the array separately :
array_name[0]=value0
array_name[1]=value1
array_name[n]=valuen
Concrete example
my_array=(A B "C" D)
echo " The first element is : ${my_array[0]}"
# assignment
my_array[2]=C
# Get all the elements in the array
echo " The elements of the array are : ${my_array[*]}"
echo " The elements of the array are : ${my_array[@]}"
Read array
Format
${ Array name [ Subscript ]}
# Such as :
valuen=${array_name[n]}
# Use @ The symbol can get all the elements in the array
echo ${array_name[@]}
Gets the length of the array
# Get the number of array elements
length=${
#array_name[@]}
# perhaps
length=${
#array_name[*]}
# Get the length of a single element of an array
lengthn=${
#array_name[n]}
Pass parameters
The format of obtaining parameters in the script is :$n.
n Represents a number ,1 For executing the first parameter of the script ,2 For executing the second parameter of the script , And so on
echo "Shell Pass parameter instance !";
echo " File name of execution :$0";
echo " The first parameter is zero :$1";
echo " The second parameter is :$2";
Special characters for processing parameters :
| Processing parameters | explain |
|---|---|
| $# | The number of parameters passed to the script |
| $* | Display all the parameters passed to the script in a single string . Such as "$*“ use 「”」 In a nutshell 、 With "$1 $2 … $n" Output all parameters in the form of . |
| $$ | The current process the script runs ID Number |
| $! | Of the last process running in the background ID Number |
| [email protected] | And ∗ phase Same as , but yes send use when Add lead Number , and stay lead Number in return return Every time individual ginseng Count . Such as " * identical , But use quotation marks , And return each parameter in quotation marks . Such as " ∗ phase Same as , but yes send use when Add lead Number , and stay lead Number in return return Every time individual ginseng Count . Such as "@“ use 「”」 In a nutshell 、 With "$1" “ 2 " … " 2" … " 2"…"n” Output all parameters in the form of . |
| $- | Show Shell Current options used , And set command Function the same . |
| $? | Display the exit status of the last command .0 No mistakes , Any other value indicates an error . |
$* And [email protected] difference :
The same thing : All references to all parameters .
Difference : Only in double quotes .
Suppose you write three parameters when the script runs 1、2、3,, be * Equivalent to 1 2 3( Passed a parameter ), and @ Equivalent to 123 ( Three parameters are passed ).
echo "Shell Pass parameter instance !";
echo " The first parameter is zero :$1";
echo " The number of parameters is :$#";
echo " The passed parameter is displayed as a string :$*";
echo "-- \$* demonstration ---"
for i in "$*"; do
echo $i
done
echo "-- \[email protected] demonstration ---"
for i in "[email protected]"; do
echo $i
done
Operator
Like any programming language , Support for multiple operators
- Arithmetic operator
- Relational operator
- Boolean operator
- String operators
- File test operators
Arithmetic operations
Native bash Simple mathematical operations are not supported , But you can do it with other commands , for example awk and expr,expr The most commonly used .
expr Is an expression calculation tool , It can be used to evaluate expressions .
Add two numbers , Note the use of back quotes , Not single quotes ':
val=`expr 2 + 2`
echo " The sum of the two is : $val"
[ $a != $b ] # return true.
a=10
b=20
val=`expr $a + $b` # 30
val=`expr $a - $b` # -10
val=`expr $a \* $b` # 200
val=`expr $b / $a` # 0
val=`expr $b % $a` # 2
if [ $a == $b ]
then
echo "a be equal to b"
fi
if [ $a != $b ]
then
echo "a It's not equal to b"
fi
- Space between expression and operator , for example 2+2 It is not right , Must be written as 2 + 2
- The complete expression is to be Two back quotes contain
- Conditional expressions should be placed between square brackets , And there should be spaces , for example :
[$a==$b]It's wrong. , Must be written as[ $a == $b ]. - Multiplication sign
*There must be a backslash in the front\To achieve multiplication ; - stay MAC in shell Of expr Grammar is :
$(( expression )), In this expression*You don't need escape symbols\.
Relationship between operation
a=10
b=20
if [ $a -eq $b ]
then
echo "$a -eq $b : a be equal to b"
else
echo "$a -eq $b: a It's not equal to b"
fi
| explain | give an example | |
|---|---|---|
| -eq | Check whether two numbers are equal , Equal return true. | [ $a -eq $b ] return false. |
| -ne | Check if two numbers are not equal , Unequal return true. | [ $a -ne $b ] return true. |
| -gt | Check whether the number on the left is greater than that on the right , If it is , Then return to true. | [ $a -gt $b ] return false. |
| -lt | Check if the number on the left is less than the number on the right , If it is , Then return to true. | [ $a -lt $b ] return true. |
| -ge | Check whether the number on the left is equal to or greater than the number on the right , If it is , Then return to true. | [ $a -ge $b ] return false. |
| -le | Check whether the number on the left is less than or equal to the number on the right , If it is , Then return to true. | [ $a -le $b ] return true. |
Boolean operation
| Operator | explain | give an example |
|---|---|---|
| ! | Non operation , Expression for true Then return to false, Otherwise return to true. | [ ! false ] return true. |
| -o | Or operations , There is an expression for true Then return to true. | [ $a -lt 20 -o $b -gt 100 ] return true. |
| -a | And operation , Both expressions are true To return to true. | [ $a -lt 20 -a $b -gt 100 ] return false. |
Logical operations
| Operator | explain | give an example |
|---|---|---|
| && | Logical AND | ·[[ $a -lt 100 && $b -gt 100 ]]` return false |
|| | Logical OR | [[ $a -lt 100 || $b -gt 100 ]] return true |
String operations
Assumed variable a by “abc”, Variable b by “efg”:
| Operator | explain | give an example |
|---|---|---|
| = | Checks if two strings are equal , Equal return true. | [ $a = $b ] return false. |
| != | Detect whether two strings are not equal , Unequal return true. | [ $a != $b ] return true. |
| -z | Check if the string length is 0, by 0 return true. | [ -z $a ] return false. |
| -n | Check whether the string length is not 0, Not for 0 return true. | [ -n "$a" ] return true. |
| $ | Check if the string is empty , Not empty return true. | [ $a ] return true. |
File test operation
file="/var/www/runoob/test.sh"
if [ -r $file ]
then
echo " Documents are readable "
else
echo " The file is unreadable "
fi
The file test operator is used to detect Unix Various attributes of the file .
Attribute detection is described as follows :
| The operator | explain | give an example |
|---|---|---|
| -b file | Check if the file is a block device file , If it is , Then return to true. | [ -b $file ] return false. |
| -c file | Check whether the file is a character device file , If it is , Then return to true. | [ -c $file ] return false. |
| -d file | Check if the file is a directory , If it is , Then return to true. | [ -d $file ] return false. |
| -f file | Check if the file is a normal file ( It's not a catalog , It's not a device file ), If it is , Then return to true. | [ -f $file ] return true. |
| -g file | Check if the file is set SGID position , If it is , Then return to true. | [ -g $file ] return false. |
| -k file | Check whether the file is set with the adhesive bit (Sticky Bit), If it is , Then return to true. | [ -k $file ] return false. |
| -p file | Check if the file is a named pipeline , If it is , Then return to true. | [ -p $file ] return false. |
| -u file | Check if the file is set SUID position , If it is , Then return to true. | [ -u $file ] return false. |
| -r file | Check whether the file is readable , If it is , Then return to true. | [ -r $file ] return true. |
| -w file | Check whether the file is writable , If it is , Then return to true. | [ -w $file ] return true. |
| -x file | Check if the file is executable , If it is , Then return to true. | [ -x $file ] return true. |
| -s file | Check if the file is empty ( Is the file size greater than 0), Not empty return true. | [ -s $file ] return true. |
| -e file | Test files ( Including directory ) Whether there is , If it is , Then return to true. | [ -e $file ] return true. |
Other checkers :
-S: Determine whether a file is socket.-L: Check whether the file exists and is a symbolic link .
echo command
# 1. Show normal string :
echo "It is a test" #
echo It is a test # The effect same as above
# 2. Show escape characters
echo "\"It is a test\"" # "It is a test"
# 3. Show variable
read name # Read a line from standard input , And assign the value of each field of the input line to shell Variable
echo "$name It is a test"
# 4. Show wrap
echo -e "OK! \n" # -e Open escape
echo "It is a test"
# 5. Show no line breaks
echo -e "OK! \c" # -e Open escape \c Don't wrap
echo "It is a test" # OK! It is a test
# 6. Show results directed to file
echo "It is a test" > myfile
# 7. Output string as is , Do not escape or take variables ( single quote )
echo '$name\"' # $name\"
# 8. Show command execution results ; Use backquotes
echo `date`
printf command
- from POSIX Standard definition , So it's better than using echo Good portability .
- Use Reference text or Space Separated parameters
- It can be outside printf Using format string , You can also specify the width of the string 、 Left and right alignment, etc .
- Don't like echo Automatically add line breaks , We can add... Manually \n.
Format :
printf format-string [arguments...]
printf "%-10s %-8s %-4s\n" full name Gender weight kg
printf "%-10s %-8s %-4.2f\n" Guo Jing male 66.1234
printf "%-10s %-8s %-4.2f\n" Yang2 guo4 male 48.6543
printf "%-10s %-8s %-4.2f\n" Guo Fu Woman 47.9876
# Output results
full name Gender weight kg
Guo Jing male 66.12
Yang2 guo4 male 48.65
Guo Fu Woman 47.99
%s,%c,%d,%fIt's all format substitutions ,%sOutput a string ,%dInteger output ,%cOutput a character ,%fOutput real number , Output in decimal form .%-10sA width of 10 Characters (- Indicates left alignment , If not, it means right alignment ), Any character will be displayed in 10 Within characters wide , If it is not enough, it will be automatically filled with spaces , More than will also show all the content .%-4.2fIt means to format it as a decimal , among .2 Finger retention 2 Decimal place .
# format-string Is double quotation mark
printf "%d %s\n" 1 "abc"
# Single quotation marks have the same effect as double quotation marks
printf '%d %s\n' 1 "abc"
# You can output without quotation marks
printf %s abcdef
# The format specifies only one parameter , But the extra parameters will still be output in this format ,format-string Be reused
printf %s abc def
printf "%s\n" abc def
printf "%s %s %s\n" a b c d e f g h i j
# without arguments, that %s use NULL Instead of ,%d use 0 Instead of
printf "%s and %d \n"
Process control
sh The process control of cannot be empty
<?php
if (isset($_GET["q"])) {
search(q);
}
else {
// Not doing anything
}
stay sh/bash You can't write that in , If else Branch has no statement execution , Don't write this else.
if
Format
if condition
then
command1
command2
...
commandN
fi
Write in a line ( For terminal command prompt ):
if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi
if else
if condition
then
command1
...
commandN
else
command
fi
if else-if else
if condition1
then
command1
elif condition2
then
command2
else
commandN
fi
Example :
a=10
b=20
if [ $a == $b ]
then
echo "a be equal to b"
elif [ $a -gt $b ]
then
echo "a Greater than b"
elif [ $a -lt $b ]
then
echo "a Less than b"
else
echo " There are no conditions that meet "
fi
for loop
for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done
Write in a line :
for var in item1 item2 ... itemN; do command1; command2… done;
for loop in 1 2 3 4 5
do
echo "The value is: $loop"
done
'''
The value is: 1
The value is: 2
The value is: 3
The value is: 4
'''
for str in This is a string
do
echo $str
done
'''
This
is
a
string
'''
while sentence
while condition
do
command
done
int=1
while(( $int<=5 ))
do
echo $int
let "int++"
done
Infinite loop
while :
do
command
done
until loop
until Loop through a series of commands until the condition is true Stop when .
until Circulation and while The cycle is the opposite of the way it's handled .
commonly while Circulation is better than until loop , But sometimes — Only in a few cases ,until Circulation is more useful .
until Grammar format :
until condition
do
command
done
Output 0 ~ 9 The number of :
a=0
until [ ! $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
Out of the loop
- break: Jump out of all loops
- continue: Jump out of current loop
function
Format
[ function ] funname [()]
{
action;
[return int;]
}
- You can take function fun() Definition , It can also be direct fun() Definition , Without any parameters .
- Parameter return , Can display plus :return return , If not , Results will be run with the last command , As return value .return Heel value n(0-255)
Example :
demoFun(){
echo " This is my first shell function !"
}
# call
demoFun
# With parameters
funWithParam(){
echo " The first parameter is zero $1 !"
echo " The second parameter is $2 !"
echo " The tenth parameter is $10 !"
echo " The tenth parameter is ${10} !" # When n>=10 when , Need to use ${n} To get the parameters .
echo " The eleventh parameter is ${11} !"
echo " The total number of parameters is $# individual !"
echo " Output all parameters as a string $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73
Special characters for processing parameters :
| Processing parameters | explain |
|---|---|
| $# | Number of arguments passed to script or function |
| $* | Display all the parameters passed to the script in a single string |
| $$ | The current process the script runs ID Number |
| $! | Of the last process running in the background ID Number |
| [email protected] | And $* identical , But use quotation marks , And return each parameter in quotation marks . |
| $- | Show Shell Current options used , And set Same command function . |
| $? | Display the exit status of the last command .0 No mistakes , Any other value indicates an error . |
Input / Output redirection
An order is usually called The standard input Where to read input , Output is written to standard Quasi output , By default , This happens to be your terminal .
Redirect command list :
| command | explain |
|---|---|
| command > file | Redirect output to file. |
| command < file | Redirect input to file. |
| command >> file | Redirect the output as an append to file. |
| n > file | Set the file descriptor to n To file. |
| n >> file | Set the file descriptor to n The file is redirected to by appending file. |
| n >& m | The output file m and n Merge . |
| n <& m | The input file m and n Merge . |
| << tag | Will start marking tag And closing marks tag Between the content as input . |
We need to pay attention to , File descriptor :
- 0 It's usually standard input (STDIN)
- 1 It's standard output (STDOUT)
- 2 Standard error output (STDERR).
# Output redirection
command1 > file1
# Input redirection
command1 < file1
- Output redirection will overwrite the contents of the file
Example
$ echo " Novice tutorial :www.runoob.com" > users
In depth understanding of Redirect
In general , Every Unix/Linux The command runs with three files open :
- Standard input file (stdin):stdin The file descriptor of is 0,Unix The program defaults from stdin Reading data .
- Standard output file (stdout):stdout The file descriptor of is 1,Unix The program defaults to stdout Output data .
- Standard error file (stderr):stderr The file descriptor of is 2,Unix The program will go to stderr Write error messages in the stream .
By default ,command > file take stdout Redirect to file,command < file take stdin Redirect to file.
stderr
# stderr Redirect to file
$ command 2>file
# stderr Append to file end of file
$ command 2>>file
# take stdout and stderr Redirect to after merge file
$ command > file 2>&1
# perhaps
$ command >> file 2>&1
# Yes stdin and stdout All redirects ( take stdin Redirect to file1, take stdout Redirect to file2.)
$ command < file1 >file2
Here Document
Here Document yes Shell A special way of redirection , Used to redirect input to an interactive Shell Script or program .
Format :
command << delimiter document delimiter
- The function is to combine two delimiter Content between (document) Pass as input to command.
- At the end of the delimiter Be sure to write at the top , There can't be any characters in front of it , There can't be any characters after it , Including spaces and tab Indent .
- At the beginning delimiter Before and after the space will be ignored .
Call in terminal
$ wc -l << EOF
> Hello
> Welcome to
> Mohe dance hall
> EOF
3
Use in script
cat << EOF Welcome to Novice tutorial www.runoob.com EOF
/dev/null file
- /dev/null It's a special document , Everything written to it will be discarded ;
- If you try to read from the file , So you can't read anything .
- however /dev/null Documents are very useful , Redirect the output of the command to it , It's going to work " No output " The effect of .
- If you want to execute a command , But I don't want to display the output on the screen , So you can redirect the output to
/dev/null.
If you want to shield stdout and stderr, It can be written like this :
$ command > /dev/null 2>&1
- there 2 and > There can be no spaces between ,
2>It means error output only when it is integrated .
References
Shell You can also include external scripts
# Grammar format
. filename # Note the number (.) There is a space between the file name and the file name
# or
source filename
example
Create two shell Script files , test1.sh and test2.sh
test1.sh The variable is declared in
name='hello'
test2.sh Call in test1.sh
# Use . Number test1.sh file
. ./test1.sh
# Or use the following include file code
# source ./test1.sh
echo "my name is :$name"
Linux The command of
https://www.runoob.com/linux/linux-command-manual.html
2022-02-15( Two )
边栏推荐
- 【八大排序③】快速排序(动图演绎Hoare法、挖坑法、前后指针法)
- Node - generate wechat permission verification configuration
- 969 interlaced string
- [leetcode] number of maximum consecutive ones
- 2022 low voltage electrician examination questions and answers
- How can programmers better plan their career development?
- Leetcode skimming: stack and queue 02 (realizing stack with queue)
- ACM教程 - 快速排序(常规 + 尾递归 + 随机基准数)
- Review notes of compilation principles
- Datawhale 社区黑板报(第1期)
猜你喜欢

Common loss function of deep learning

The pain of Xiao Sha

Slf4j print abnormal stack information

【会议资源】2022年第三届自动化科学与工程国际会议(JCASE 2022)

ACM教程 - 快速排序(常规 + 尾递归 + 随机基准数)
![[eight sorting ③] quick sorting (dynamic graph deduction Hoare method, digging method, front and back pointer method)](/img/c2/7ebc67e9b886e3baf3c98489bf9bce.png)
[eight sorting ③] quick sorting (dynamic graph deduction Hoare method, digging method, front and back pointer method)

excel数据透视表
![[conference resources] the Third International Conference on Automation Science and Engineering in 2022 (jcase 2022)](/img/a6/a2afdf9e18255c9171f61bf074998b.png)
[conference resources] the Third International Conference on Automation Science and Engineering in 2022 (jcase 2022)
![[eight sorts ①] insert sort (direct insert sort, Hill sort)](/img/8d/2c45a8fb582dabedcd2658cd7c54bc.png)
[eight sorts ①] insert sort (direct insert sort, Hill sort)

AIX存储管理之卷组的创建(一)
随机推荐
Comprehensive broadcast of global and Chinese markets 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese markets for maritime services 2022-2028: Research Report on technology, participants, trends, market size and share
SSO single sign on implementation.
What does open loop and closed loop mean?
BPR (Bayesian personalized sorting)
The 8-year salary change of testers makes netizens envy it: you pay me one year's salary per month
What are the differences between software testers with a monthly salary of 7K and 25K? Leaders look up to you when they master it
King combat power query renamed toolbox applet source code - with traffic main incentive advertisement
How does schedulerx help users solve the problem of distributed task scheduling?
Deb file installation
cookie、session、tooken
Leetcode skimming: binary tree 01 (preorder traversal of binary tree)
@Valid parameter verification does not take effect
RFID让固定资产盘点更快更准
S32Kxxx bootloader之UDS bootloader
How to type spaces in latex
Global and Chinese market of picture archiving and communication system (PACS) 2022-2028: Research Report on technology, participants, trends, market size and share
Friends circle community program source code sharing
449 original code, complement code, inverse code
Leetcode skimming: stack and queue 05 (inverse Polish expression evaluation)