当前位置:网站首页>Getting started with shell Basics
Getting started with shell Basics
2022-06-22 13:22:00 【Xiaotiantian 666】
Why study Shell Programming
1、Linux When the operation and maintenance engineer is managing the server cluster , You need to write Shell Program for Server Management .
2、 about javaEE and python For the programmer , The need for work , Your boss will ask you to write some Shell Script for program or server maintenance , For example, write a script to back up the database regularly .
3、 For big data programmers , You need to write Shell Program to manage clusters .
Shell What is it?
Shell Is a command interpreter , It provides a way for users to Linux The interface system program that the kernel sends a request to run the program , Users can use Shell To start up 、 Hang up 、 Stop even writing some programs .
Shell How the script is executed
- Script format requirements
1、 Script to #!/bin/bash
2、 Scripts need to have executable rights - Common execution methods of scripts
The way 1: Enter the absolute or relative path of the script
explain : First, give the script +x jurisdiction , Then execute the script
such as :./hello.sh Or use absolute path /root/shcode/hello.sh
The way 2:sh+ Script
explain : Not scripted +x jurisdiction , Then execute the script
such as :sh hello.sh You can also use absolute paths
shell Variable
- Define variable rules
Variable name without dollar sign
Only English letters can be used for naming , Numbers and underscores , The first character cannot start with a number .
No spaces in between , You can use underscores (_).
You can't use punctuation .
Out of commission bash Keywords in ( You can use help Command to view reserved keywords )
1、 Defining variables : Variable name = value
2、 Revoke variables :unset Variable
3、 Declare static variables :readonly Variable , Be careful : You can't unset
4、A= `date `` The quotation marks , Run the command inside , And return the result to the variable A
5、A=$(date) Equivalent to backquotes
Set the environment variable
- Basic grammar
1、export Variable name = A variable's value ( Function description : take shell Variable output is environment variable / Global variables )
2、source The configuration file ( Function description : Let the modified configuration options take effect immediately )
3、echo $ Variable name ( Function description : Query the value of the environment variable )
Be careful : At output TOMCAT_HOME Before environment variable , It needs to take effect
source /etc/profile
Position parameter variable
When we execute a shell Script time , If you want to get the parameter information of the command line , You can use the position parameter variable .
such as :./myshell.sh 100 200, This is an execution shell The command line , Can be in myshell Get the parameter information in the script .
- Basic grammar
1、$ n:n Is the number ,$0 For the order itself ,$1- $ 9 Represents the first to ninth parameters , More than ten parameters need to be enclosed in braces , Such as :$ {10}.
2、$ *: This variable represents all the parameters on the command line ,$* Treat all parameters as a whole .
3、 [email protected]: This variable also represents all the parameters on the command line , however [email protected] Treat each parameter differently .
4、 $#: This variable represents the number of all parameters on the command line .
Predefined variables
Namely shell Variables that have been defined by the designer in advance , Can be directly in shell Use in script
- Basic grammar
1、 $$: The process number of the current process (PID)
2、 $!: The process number of the last process running in the background (PID)
3、 $?: Return status of last executed command . If the value of this variable is 0, Prove that the last command was executed correctly ; If the value of this variable is not 0( Which number is it , It's up to the order itself ), The last command was executed incorrectly .
Operator
- Basic grammar
1、“$(( Operator ))” or “ $[ Operator ]” perhaps expr m + n
2、 Be careful expr Space between operators
3、expr m - n
4、expr \ *,/,% ride , except , Remainder
Judge the condition
- Basic grammar
if [ condition ]
then
...
elif [ condition ]
then
...
fi( Be careful condition Space before and after )
# Not empty return true, You can use $? verification (0 by true,>1 by false)
- Application example
[ test ] return true
[] return false
[ condition ] && echo OK || echo notok Conditions met , Execute the following statement - Judgment statement
1、= String comparison
2、 A comparison of two integers
-lt Less than
-le Less than or equal to
-gt Greater than
-ge Greater than or equal to
-ne It's not equal to
3、 Judge according to the file authority
-r Have read permission
-w Have the right to write
-x Have the authority to execute
4、 Judge according to the document type
-f The file exists and is a regular file
-e File exists
-d The file exists and is a directory - Case study


case sentence
- Basic grammar
case $ Variable name in
" value 1" )
If the value of the variable is equal to the value 1, Then execute the procedure 1
;;
" value 2")
If the value of the variable is equal to the value 2, Then execute the procedure 2
;;
... Omit other branches ...
*)
If none of the values of the variables are above , Then execute this procedure
;;
esac


for loop
- Basic grammar
# grammar 1
for Variable in value 1 value 2 value 3...
do
Program
done
# grammar 2
for(( Initial value ; Cycle control conditions ; Variable change ))
do
Program
done
while loop
- Basic grammar
while [ Conditional judgment ]# Space inside parentheses
do
Program ...
done
read Read console input
- Basic grammar
read( Options )( Parameters )
Options :
-p: Specify the prompt when reading the value
-t: Specifies the time to wait while reading the value ( second ), If it is not entered in the specified time , I don't wait .
Parameters : Specifies the variable name of the read value


function
shell Programming is like other programming languages , There are system functions , You can also customize functions . In system function , Let's introduce two .
System function
- basename Basic grammar
basename [pathname] [suffix]
basename [string] [suffix]
basename The command will delete all prefixes including the last (‘/’) character , Then display the string .
Options :
suffix For the suffix , If suffix Designated ,basename Will pathname or string Medium suffix Get rid of .
- dirname Basic grammar
function : Return to full path last / The front part of , Commonly used in the return path part
dirname File absolute path : Remove filename from given filename with absolute path ( Non catalogue part ), Then return to the rest of the path ( Part of the catalog )
Custom function - Basic grammar
[function] funname[()]
{
Action;
[return int;]
}
Call to write the function name directly :funname [ value ]
- Case study : Calculate the sum of the two input parameters ( Get dynamic ),getSum


Shell String
The string is shell The most commonly used and useful data types in programming , Strings can be single - booted , You can also use double quotes , You can also use no quotes .
Single quotation marks :
Any character in a single quotation mark will be output as is , Variables in a single quoted string are invalid ;
A single quotation mark cannot appear in a single quotation mark string , But in pairs , Used as a string concatenation .Double quotes :
You can have variables in double quotes
Escape characters can appear in double quotes
# Declaration string
str1="hello world 1"
str2="hello world 2"
# String splicing -- Double quotes
name='helloworld'
name1="hello, "$name" !"
name2="hello, ${name} !"
# String splicing -- Single quotation marks
passwd=’123456‘
passwd1=’hello, ‘$passwd’ !‘
passwd2='hello, ${passwd} !'
echo $passwd2 # hello,${passwd} !
# Length of string
email="[email protected]"
echo ${
#email}
echo ${
email:1:4}
Shell Array
bash Supports one dimensional array ( Multidimensional arrays are not supported ), And there's no limit to the size of the array
The subscripts of array elements are 0 Numbered starting . To get the elements in an array, you need to use subscripts , Subscripts can be integers or arithmetic expressions , Its value should be greater than or equal to 0 .
# Define an array Parentheses are used to represent arrays , For array elements “ Space ” Symbol split
Array name =( value 1 value 2 .... value n)
favs=(" football " " Basketball " " Table Tennis " " The bowling ball ")
# Read array ${ Array name [ Subscript ]}
fav=${
favs[1]}
# Use @ The symbol can get all the elements in the array
echo ${
favs[@]}
# Gets the length of the array
length1=${
#favs[@]}
length2=${
#favs[*]}
Shell Notes
With # The first line is the comment , Will be ignored by the interpreter .
Add one... To each line # Number to set multiline comment
#-----------------------
# This is a comment
#author:
#site:
#-----------------------
#### Server configuration -start ####
#
#
#
#
#
#### Server configuration -end ####
# Special multiline comments
:<<EOF
The comment ...
The comment ...
The comment ...
EOF
:<<!
The comment ...
The comment ...
The comment ...
!
Shell Parameter passing
perform Shell Script time , Pass parameters to script , The format of obtaining parameters in the script is :$n.n Represents a number
| Processing parameters | Parameter description |
|---|---|
| $# | The number of parameters passed to the script |
| $* | 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 |
| $? | Display the exit status of the last command .0 No mistakes , Any other value indicates an error . |
| $0 | File name of execution |
#!/bin/bash
echo "Shell Pass parameter instance !"
echo " File name of execution :$0"
echo " The first parameter is zero :$1"
echo " The second parameter is :$2"
echo " The third parameter is zero :$3"
# ./hello.sh 11 22 33 44
边栏推荐
- Rf5.0 new content quick view
- Reddit product director: a practical guide for NFT members for Web3 creators
- 47. Permutations II
- redis修改密码,及启动、查看等操作
- 155. Min Stack
- 从零开始写一个契约测试工具——数据库设计
- leetcode 854. String with similarity K
- redis主备配置dockercompose版
- Write a contract testing tool from scratch
- 448. Find All Numbers Disappeared in an Array
猜你喜欢

leetcode 11. 盛最多水的容器

Redis active / standby configuration dockercompose version

Leetcode subsequence / substring problem

Heavyweight live | bizdevops: the way to break the technology situation under the tide of digital transformation

Reconstruction practice of complex C-end project of acquisition technology

130. Surrounded Regions

leetcode-背包问题

Shell基础入门

In June, China database industry analysis report was released! Smart wind, train storage and regeneration

redis主备配置dockercompose版
随机推荐
Secondary development of robotframework -- socket push real-time log
Writing a contract testing tool from scratch -- database design
leetcode 85. 最大矩形
Windows system installs multiple MySQL versions (without uninstalling the original version), and the old and new versions are compatible.
Sap-mm-migo 311 intra factory transfer inventory
leetcode 854. 相似度为 K 的字符串
AcWing 241 楼兰图腾(树状数组详解)
693. Binary Number with Alternating Bits
448. Find All Numbers Disappeared in an Array
Leetcode subsequence / substring problem
think php环境搭建笔记
Detailed installation tutorial of MySQL 8.0.29 under windows to solve the problem that vcruntime140 cannot be found_ 1.dll、plugin caching_ sha2_ password could not be loaded
Leetcode daily question 202110
使用SQLAlchemy进行组合分页查询
Secondary development of robotframework -- file parsing
MAUI使用Masa blazor组件库
47. Permutations II
vs code
6月《中国数据库行业分析报告》发布!智能风起,列存更生
leetcode每日一题202110