当前位置:网站首页>Shell - introduction, variables, and basic syntax
Shell - introduction, variables, and basic syntax
2022-04-23 17:06:00 【Magic Flute love】
Shell
Shell It's a command line interpreter , It accepts application and user commands , And then invoke the kernel of the operating system .
Linux Provided Shell Parser has
[bd@localServer ~]$ cat /etc/shells
/bin/sh
/bin/bash
/sbin/nologin
/bin/dash
/bin/tcsh
/bin/csh
bash and sh The relationship between , call sh What is actually called is bash, They are soft connections
Centos The default parser is bash
[bd@localServer ~]$ echo $SHELL
/bin/bash
Shell introduction
Script format : Script to #!/bin/bash start ( Specify the parser )
Common execution methods of scripts ( With /home/test.sh For example )
The first one is : use bash or sh+ Relative or absolute path of script ( Don't assign script +x jurisdiction )
sh+ Relative path of script
sh test.sh
sh+ The absolute path of the script
sh /home/test.sh
bash+ Relative path of script
bash test.sh
bash+ The absolute path of the script
bash /home/test.sh
The second kind : Execute the script using the absolute or relative path of the input script ( Must have executable permissions +x)
# Relative paths
[bd@localServer ~]$ ./test.sh
# Absolute path
[bd@localServer ~]$ /home/test.sh
Be careful : First execution method , The essence is bash Parsers help you execute scripts , So the script itself does not need execution permission . The second method of execution , The essence is that scripts need to be executed by themselves , Therefore, execution permission is required .
Shell The variables in the
System variables
Common system variables
H O M E 、 HOME、 HOME、PWD、 S H E L L 、 SHELL、 SHELL、USER etc.
## View the value of the system variable
[bd@localServer ~]$ echo $HOME
/home/bd
## Show the current Shell All variables in :set
[bd@localServer ~]$ set
BASH=/bin/bash
BASH_ALIASES=()
BASH_ARGC=()
BASH_ARGV=()
...
Custom variable
Basic grammar
(1) Defining variables : Variable = value
(2) Revoke variables :unset Variable
(3) Declare static variables :readonly Variable , Be careful : You can't unset
Variable definition rules
(1) Variable names can be alphabetized 、 Numbers and underscores , But it can't start with a number , Environment variable name is recommended to be capitalized .
(2) No spaces on both sides of equal sign
(3) stay bash in , Variable default type is string type , No direct numerical operation .
(4) Value of variable if there is a space , Double or single quotes are required .
Case practice
## Defining variables A
[bd@localServer ~]$ A=5
[bd@localServer ~]$ echo $A
5
## To the variable A Reassign
[bd@localServer ~]$ A=8
[bd@localServer ~]$ echo $A
8
## Revoke variables A
[bd@localServer ~]$ unset A
[bd@localServer ~]$ echo $A
## Declare static variables B=2, You can't unset
[bd@localServer ~]$ readonly B=2
[bd@localServer ~]$ echo $B
2
[bd@localServer ~]$ B=9
-bash: B: readonly variable
## stay bash in , Variable default type is string type , No direct numerical operation
[bd@localServer ~]$ C=1+2
[bd@localServer ~]$ echo $C
1+2
## Value of variable if there is a space , Double or single quotes are required
[bd@localServer ~]$ D=I love sanguo
-bash: world: command not found
[bd@localServer ~]$ D="I love sanguo"
[bd@localServer ~]$ echo $A
I love sanguo
## Variable can be promoted to global environment variable , For other purposes Shell Program usage
export Variable name
[bd@localServer ~]$ vim test.sh
test.sh Add to file echo $B
#!/bin/bash
echo "helloworld"
echo $B
[bd@localServer ~]$ ./helloworld.sh
Helloworld
Found no printout variables B Value .
[bd@localServer ~]$ export B
[bd@localServer ~]$ ./helloworld.sh
helloworld
2
Special variables :$n
Basic grammar
$n
Function description :n Is the number ,$0 Represents the script name ,$1- 9 generation surface The first One To The first Nine individual ginseng Count , Ten With On Of ginseng Count Need to be want use Big enclosed Number package contain , Such as 9 Represents the first to ninth parameters , More than ten parameters need to be enclosed in braces , Such as 9 generation surface The first One To The first Nine individual ginseng Count , Ten With On Of ginseng Count Need to be want use Big enclosed Number package contain , Such as {10}
Case practice
## Output the script file name 、 Input parameters 1 And input parameters 2 Value
[bd@localServer ~]$ touch parameter.sh
[bd@localServer ~]$ vim parameter.sh
#!/bin/bash
echo "$0 $1 $2"
[bd@localServer ~]$ chmod 777 parameter.sh
[bd@localServer ~]$ ./parameter.sh cls xz
./parameter.sh cls xz
Special variables :$#
Basic grammar
$#
Function description : Get the number of all input parameters , Commonly used in cycles
Case practice
## Get the number of input parameters
[bd@localServer ~]$ vim parameter.sh
#!/bin/bash
echo "$0 $1 $2"
echo $#
[bd@localServer ~]$ chmod 777 parameter.sh
[bd@localServer ~]$ ./parameter.sh cls xz
parameter.sh cls xz
2
Special variables :KaTeX parse error: Undefined control sequence: \* at position 1: \̲*̲、@
Basic grammar
$*
Function description : This variable represents all the parameters on the command line ,$* Treat all parameters as a whole
$@
Function description : This variable also represents all the parameters on the command line , however $@ Treat each parameter differently
Case practice
## Print all parameters entered
[bd@localServer ~]$ vim parameter.sh
#!/bin/bash
echo "$0 $1 $2"
echo $#
echo $*
echo $@
[bd@localServer ~]$ bash parameter.sh 1 2 3
parameter.sh 1 2
3
1 2 3
1 2 3
Special variables :$?
Basic grammar
$?
Function description : 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 .
Case practice
## Judge helloworld.sh Whether the script is executed correctly
[bd@localServer ~]$ ./helloworld.sh
hello world
[bd@localServer ~]$ echo $?
0
Operator
Basic grammar
(1)“ ( ( shipment count type ) ) ” or “ (( Arithmetic expression ))” or “ (( shipment count type ))” or “[ Arithmetic expression ]”
(2)expr + , - , \*, /, % Add , reduce , ride ( stay expr Must be used later \*, stay [ shipment count type ] and [ Arithmetic expression ] and [ shipment count type ] and (( Arithmetic expression )), except , Remainder
Be careful :expr Space between operators
Case practice :
## Calculation 3+2 Value
[bd@localServer ~]$ expr 2 + 3
5
## Calculation 3-2 Value
[bd@localServer ~]$ expr 3 - 2
1
## Calculation (2+3)X4 Value
### (a)expr One step calculation
[bd@localServer ~]$ expr `expr 2 + 3` \* 4
20
###(b) use $[ Arithmetic expression ] The way
[bd@localServer ~]$ S=$[(2+3)*4]
[bd@localServer ~]$ echo $S
20
conditional
Basic grammar
[ condition ]( Be careful condition Space before and after )
Be careful : If the condition is not empty, it is true,[ test ] return true,[] return false.
Common judgment conditions
Compare two integers
= String comparison
-lt Less than (less than) -le Less than or equal to (less equal)
-eq be equal to (equal) -gt Greater than (greater than)
-ge Greater than or equal to (greater equal) -ne It's not equal to (Not equal)
Judge according to the file authority
-r Have read permission (read) -w Have the right to write (write)
-x Have the authority to execute (execute)
Judge according to the document type
-f The file exists and is a regular file (file)
-e File exists (existence)
-d The file exists and is a directory (directory)
Case practice
## 23 Greater than or equal to 22
[bd@localServer ~]$ [ 23 -ge 22 ]
[bd@localServer ~]$ echo $?
0
## test.sh Whether you have write permission
[bd@localServer ~]$ [ -w helloworld.sh ]
[bd@localServer ~]$ echo $?
0
## /home/bd/cls.txt Does the file in the directory exist
[bd@localServer ~]$ [ -e /home/bd/cls.txt ]
[bd@localServer ~]$ echo $?
1
## Multi condition judgment (&& Indicates that the previous command is executed successfully , To execute the last command ,|| Indicates that after the execution of the previous command fails , To execute the next command )
[bd@localServer ~]$ [ condition ] && echo OK || echo notok
OK
[bd@localServer ~]$ [ condition ] && [ ] || echo notok
notok
Process control
if Judge
Basic grammar
if [ Conditional judgment ];then
Program
fi
perhaps
if [ Conditional judgment ]
then
Program
fi
matters needing attention :
(1)[ Conditional judgment ], There must be a space between the bracket and the conditional judgment
(2)if Space after
Case practice
## Enter a number , If it is 1, The output this is 1, If it is 2, The output this is 2, If other , Output nothing .
[bd@localServer ~]$ touch if.sh
[bd@localServer ~]$ vim if.sh
#!/bin/bash
if [ $1 -eq "1" ]
then
echo "this is 1"
elif [ $1 -eq "2" ]
then
echo "this is 2"
fi
[bd@localServer ~]$ chmod 777 if.sh
[bd@localServer ~]$ ./if.sh 1
this is 1
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
matters needing attention :
-
case Line ending must be a word “in”, Each pattern match must be in right parenthesis “)” end .
-
Double a semicolon “;;” Indicates the end of the command sequence , amount to java Medium break.
-
final “*)” Represents the default mode , amount to java Medium default.
Case practice
## Enter a number , If it is 1, The output one, If it is 2, The output two, If other , Output other.
[bd@localServer ~]$ touch case.sh
[bd@localServer ~]$ vim case.sh
#!/bin/bash
case $1 in
"1")
echo "one"
;;
"2")
echo "two"
;;
*)
echo "other"
;;
esac
[bd@localServer ~]$ chmod 777 case.sh
[bd@localServer ~]$ ./case.sh 1
one
for loop
Basic grammar 1
for (( Initial value ; Cycle control conditions ; Variable change ))
do
Program
done
Case practice
## from 1 Add to 100
[bd@localServer ~]$ touch for1.sh
[bd@localServer ~]$ vim for1.sh
#!/bin/bash
s=0
for((i=0;i<=100;i++))
do
s=$[$s+$i]
done
echo $s
[bd@localServer ~]$ chmod 777 for1.sh
[bd@localServer ~]$ ./for1.sh
5050
Basic grammar 2
for Variable in value 1 value 2 value 3…
do
Program
done
Case practice
## 1、 Print all input parameters
[bd@localServer ~]$ touch for2.sh
[bd@localServer ~]$ vim for2.sh
#!/bin/bash
# Print digit
for i in $*
do
cho "this is $i"
done
[bd@localServer ~]$ chmod 777 for2.sh
[bd@localServer ~]$ bash for2.sh 1 2 bd
this is 1
this is 2
this is bd
## 2、 Compare $* and $@ difference
### 2.a、$* and $@ Represents all parameters passed to a function or script , Not double quoted “” Inclusion time , Are subject to $1 $2 …$n Output all parameters in the form of .
[bd@localServer ~]$ touch for.sh
[bd@localServer ~]$ vim for.sh
#!/bin/bash
for i in $*
do
echo "this is $i "
done
for j in $@
do
echo "that is $j"
done
[bd@localServer ~]$ bash for.sh 1 2 bd
this is 1
this is 2
this is bd
that is 1
that is 2
that is bd
## 2.b、 When they are double quoted “” Inclusion time ,“$*” All parameters will be taken as a whole , With “$1 $2 …$n” Output all parameters in the form of ;“$@” Separate parameters , With “$1” “$2”…”$n” Output all parameters in the form of .
[bd@localServer ~]$ vim for.sh
#!/bin/bash
#$* All parameters in are considered as a whole , So this for Loop only once
for i in "$*"
do
echo "this is $i"
done
#$@ Each parameter in is considered independent , therefore “$@” There are several parameters in , It's going to cycle a couple of times
for j in "$@"
do
echo "that is $j"
done
[bd@localServer ~]$ chmod 777 for.sh
[bd@localServer ~]$ bash for.sh 1 2 bd
this is 1 2 bd
that is 1
that is 2
that is bd
while loop
Basic grammar
while [ Conditional judgment ]
do
Program
done
Case practice
## from 1 Add to 100
[bd@localServer ~]$ touch while.sh
[bd@localServer ~]$ vim while.sh
#!/bin/bash
s=0
i=1
while [ $i -le 100 ]
do
s=$[$s+$i]
i=$[$i+1]
done
echo $s
[bd@localServer ~]$ chmod 777 while.sh
[bd@localServer ~]$ ./while.sh
5050
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 you don't fill in, you will wait indefinitely
Parameters
Variable : Specifies the variable name of the read value
Case practice
### Tips 7 Seconds , Read the name entered by the console
[bd@localServer ~]$ touch read.sh
[bd@localServer ~]$ vim read.sh
#!/bin/bash
read -t 7 -p "Enter your name in 7 seconds " NAME
echo $NAME
[bd@localServer ~]$ ./read.sh
Enter your name in 7 seconds test
test
function
System function
basename
Basic grammar
## Function description :basename The command will delete all prefixes including the last (‘/’) character , Then display the string .
basename [string / pathname] [suffix]
## Options :
## suffix For the suffix , If suffix Designated ,basename Will pathname or string Medium suffix Get rid of .
Case practice
## Intercept this /home/bd/test.txt File name of the path
[bd@localServer ~]$ basename /home/bd/test.txt
test.txt
[bd@localServer ~]$ basename /home/bd/test.txt .txt
test
dirname
Basic grammar
## Function description : Remove filename from given filename with absolute path ( Non catalog part ), Then return to the rest of the path ( Part of the catalog )
dirname File absolute path
Case practice
## obtain test.txt Path to file
[bd@localServer ~]$ dirname /home/bd/test.txt
/home/bd
Custom function
Basic grammar
## All in brackets are optional , However, it is generally not omitted function And parentheses
[ function ] funname[()]
{
Action;
[return int;]
}
funname
Experience and skill
(1) Must be before calling function place , Declare function first ,shell The script is run line by line . It doesn't compile first like any other language .
(2) Function return value , Only through $? System variable acquisition , Can display plus :return return , If not , Results will be run with the last command , As return value .return Heel value n(0-255)
Case practice
## Calculate the sum of the two input parameters
[atguigu@hadoop101 datas]$ touch fun.sh
[atguigu@hadoop101 datas]$ vim fun.sh
#!/bin/bash
function sum()
{
s=0
s=$[ $1 + $2 ]
echo "$s"
}
read -p "Please input the number1: " n1;
read -p "Please input the number2: " n2;
sum $n1 $n2;
[bd@localServer ~]$ chmod 777 fun.sh
[bd@localServer ~]$ ./fun.sh
Please input the number1: 2
Please input the number2: 5
7
版权声明
本文为[Magic Flute love]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231704450799.html
边栏推荐
- Linux MySQL data timing dump
- ClickHouse-数据类型
- PHP高效读大文件处理数据
- websocket
- C# Task. Delay and thread The difference between sleep
- Getting started with JDBC
- EF core in ASP Generate core priority database based on net entity model
- Detailed explanation of C webpai route
- Dancenn: overview of byte self-developed 100 billion scale file metadata storage system
- 如何用Redis实现分布式锁?
猜你喜欢

Dancenn: overview of byte self-developed 100 billion scale file metadata storage system

How vscode compares the similarities and differences between two files

信息摘要、数字签名、数字证书、对称加密与非对称加密详解

Nodejs reads the local JSON file through require. Unexpected token / in JSON at position appears

Nifi fast installation and file synchronization

Installing labellmg tutorial in Windows

vscode如何比较两个文件的异同
![[PROJECT] small hat takeout (8)](/img/54/0187eeb637f4dcd4ad3969b00e2b77.png)
[PROJECT] small hat takeout (8)

Shell script -- shell programming specification and variables

SQL database
随机推荐
Solution architect's small bag - 5 types of architecture diagrams
Expression "func" tSource, object "to expression" func "tSource, object" []
Paging SQL
计算饼状图百分比
STM32__03—初识定时器
[registration] tf54: engineer growth map and excellent R & D organization building
文件操作《二》(5000字总结篇)
Talk about browser cache control
手写事件发布订阅框架
PostgreSQL列存与行存
SQL database
Zhimeng dedecms security setup Guide
How much do you know about the process of the interview
JS to find the character that appears three times in the string
Your brain expands and shrinks over time — these charts show how
Feign report 400 processing
Detailed explanation of Niuke - Gloves
El date picker limits the selection range from the current time to two months ago
Nodejs installation and environment configuration
[pimf] openharmony paper Club - what is the experience of wandering in ACM survey