当前位置:网站首页>Shell script Basics

Shell script Basics

2022-06-13 07:39:00 _ seven seven

From inside to outside : Hardware - linux kernel - shell(cd、ls…) - Outer application ;

Shell Parser

1、linux Provided shell Parser :

$ cat /etc/shells 

/bin/sh
/bin/bash
/sbin/nologin
/bin/dash
/bin/tcsh
/bin/csh

2、bash and sh The relationship between

$ cd /bin/
$ ll | grep bash

-rwxr-xr-x. 1 root root 941880 5 month   11 2016 bash
lrwxrwxrwx. 1 root root      4 5 month   27 2017 sh -> bash

3、Centos Default parser :bash

$ echo $SHELL

/bin/bash

Shell Script

1、 Script format

Script to #!/bin/bash start , Specify the parser

2、 demand : establish shell Script , Output helloworld


$ touch helloworld.sh
$ vi helloworld.sh

 stay helloworld.sh Enter the following in 
#! /bin/bash
echo "helloworld test"

Script execution :

 The first one is :
 use bash or sh+ Relative or absolute path of script ( Don't assign script +x jurisdiction )
$ sh helloworld.sh 
$ bash helloworld.sh

 The second kind :
 Execute the script using the absolute or relative path of the input script ( Must have executable permissions +x)
./helloworld.sh
 If you don't have enough authority  
$ chmod 777 helloworld.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 .

3、 Multiline command processing

(1) demand :

stay /home/test/ Create one in the directory test.txt, stay test.txt Add to file “I love shell”.

$ touch batch.sh
$ vi batch.sh

 stay batch.sh Enter the following in 
#!/bin/bash

cd /home/test
touch test.txt
echo "I love shell" >>cls.txt

Shell Variable

1、 Common system variables

H O M E 、 HOME、 HOMEPWD、 S H E L L 、 SHELL、 SHELLUSER etc.

Check the variable :

$ echo $HOME
$ echo $PWD
...

2、 Custom variable

1. Basic grammar 
(1) Defining variables :  Variable = value  
(2) Revoke variables : unset  Variable 
(3) Declare static variables : readonly  Variable , Be careful : You can't  unset

2. 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 .

(1) Defining variables A

$ A=5
$ echo $A
5

(2) To the variable A Reassign

$ A=8
$ echo $A
8

(3) Revoke variables A

$ unset A
$ echo $A

(4) Declare static variables B=2, You can't unset

$ readonly B=2
$ echo $B
2
B=9
-bash: B: readonly variable

(5) stay bash in , Variable default type is string type , No direct numerical operation

$ C=1+2
$ echo $C
1+2

(6) Value of variable if there is a space , Double or single quotes are required

$ D=I love shell
-bash: world: command not found

$ D="I love shell"
$ echo $D
I love shell

(7) Variable can be promoted to global environment variable , For other purposes Shell Program usage

export Variable name

$ echo $D
I love shell
---

./helloworld.sh
helloworld shell

---
$ vim helloworld.sh 

 stay helloworld.sh Add to file echo $D

#!/bin/bash

echo "helloworld"
echo $D

---

$ ./helloworld.sh 
Helloworld
 Found no printout variables D Value .

---

export D
$ ./helloworld.sh 
helloworld
I love shell


Special variables :$n

1. 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 , 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 , 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 , Ten With On Of ginseng Count Need to be want use Big enclosed Number package contain , Such as {10})

2. Case practice
(1) Output the script file name 、 Input parameters 1 And input parameters 2 Value


[[email protected] datas]$ touch parameter.sh 
[[email protected] datas]$ vim parameter.sh

#!/bin/bash
echo "$0 $1 $2"

---

$ chmod 777 parameter.sh
$ ./parameter.sh AA BB
./parameter.sh AA BB

Special variables :$#

1. Basic grammar
$# ( Function description : Get the number of all input parameters , Commonly used in cycles ).

$ vim parameter.sh

#!/bin/bash
echo "$0 $1 $2"
echo $#

---
$ chmod 777 parameter.sh

[[email protected] datas]$ ./parameter.sh AA BB
parameter.sh AA BB
2

Special variables : ∗ 、 *、 @

1. Basic grammar

∗ ( work can Sketch Statement : this individual change The amount generation surface life Make That's ok in the Yes Of ginseng Count , * ( Function description : This variable represents all the parameters on the command line , work can Sketch Statement this individual change The amount generation surface life Make That's ok in the Yes Of ginseng Count ,* Treat all parameters as a whole )

@ ( work can Sketch Statement : this individual change The amount also generation surface life Make That's ok in the Yes Of ginseng Count , No too @ ( Function description : This variable also represents all the parameters on the command line , however @ work can Sketch Statement this individual change The amount also generation surface life Make That's ok in the Yes Of ginseng Count , No too @ Treat each parameter differently )

2. Case practice
(1) Print all parameters entered

$ vim parameter.sh

#!/bin/bash
echo "$0 $1 $2"
echo $#
echo $*
echo [email protected]

---
$ bash parameter.sh 1 2 3
parameter.sh 1 2
3
1 2 3
1 2 3

Special variables :$?

1. 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 .)

2. Case practice

​ (1) Judge helloworld.sh Whether the script is executed correctly

$ ./helloworld.sh 
hello world

$ echo $?
0

Operator

1. Basic grammar

(1)“ $(( Arithmetic expression )) ” or “ $[ Arithmetic expression ] ”

(2)expr + , - , *, /, % Add , reduce , ride , except , Remainder

Be careful :expr Space between operators

Case practice :

(1) Calculation 3+2 Value

$ expr 2 + 3
5

(2) Calculation 3-2 Value

$ expr 3 - 2 
1

(3) Calculation (2+3)* 4 Value

(a)expr One step calculation

$ expr `expr 2 + 3` \* 4
20

(b) use $[ Arithmetic expression ] The way

S=$[(2+3)*4]
echo $S

conditional

1、 Basic grammar

[ condition ]( Be careful condition Space before and after )

Be careful : If the condition is not empty, it is true,[ abc ] return true,[] return false.

2、 Common judgment conditions

(1) 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)

(2) 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)

(3) 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)

3、 Case practice

​ (1)23 Greater than or equal to 22

$ [ 23 -ge 22 ]
$ echo $?
0

(2)helloworld.sh Whether you have write permission

$ [ -w helloworld.sh ]
$ echo $?
0

(3)/home/test/test.txt Does the file in the directory exist

$ [ -e /home/test/test.txt ]
$ echo $?
1

(4) 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 )

&& echo OK || echo notok
OK

$ [ condition ] && [ ] || echo notok
notok

Process control ( a key )

if Judge

1. 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

(1) Enter a number , If it is 1, The output print 1, If it is 2, The output print 2 , If other , Output nothing .

$ touch if.sh
$ vim if.sh


#!/bin/bash

if [ $1 -eq "1" ]
then
	echo "print 1"
elif [ $1 -eq "2" ]
then
	echo "print 2"
fi

$ chmod 777 if.sh 
$ ./if.sh 1

case sentence

1. 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

$ chmod 777 case.sh
$ ./case.sh 1
1

for loop

1、 Basic grammar 1

for ((  Initial value ; Cycle control conditions ; Variable change  )) 
do 
	 Program  
done

Case practice

(1) from 1 Add to 100

$ touch for1.sh
$ vim for1.sh


#!/bin/bash

s=0
for((i=0;i<=100;i++))
do
	s=$[$s+$i]
done
echo $s

$ chmod 777 for1.sh 
$ ./for1.sh 
“5050”

2、 Basic grammar 2

for  Variable  in  value 1  value 2  value 3… 
do 
	 Program  
done

(1) Print all input parameters

$ touch for2.sh
$ vim for2.sh

#!/bin/bash
# Print digit 

for i in $*
do
	echo "print $i "
done

$ chmod 777 for2.sh 
$ bash for2.sh aa bb cc

3、 Compare ∗ and * and and @ difference

(a) ∗ and * and and @ Represents all parameters passed to a function or script , Not double quoted “” Inclusion time , Are subject to $1 2 … 2 … 2n Output all parameters in the form of .

$ touch for.sh
$ vim for.sh


#!/bin/bash

for i in $*
do
    echo "$* print $i "
done

for j in [email protected]
do
    echo "[email protected] print $j"
done

$ bash for.sh AA BB CC

(b) When they are double quoted “” Inclusion time ,“$*” All parameters will be taken as a whole , With “$1 2 … 2 … 2n” Output all parameters in the form of ;“[email protected]” Separate parameters , With “$1” “ 2 ” … ” 2”…” 2n” Output all parameters in the form of .

$ vim for.sh

#!/bin/bash

for i in "$*"
#$* All parameters in are considered as a whole , So this for Loop only once 
do
    echo "ban zhang love $i"
done

for j in "[email protected]"
#[email protected] Each parameter in is considered independent , therefore “[email protected]” There are several parameters in , It's going to cycle a couple of times 
do
    echo "ban zhang love $j"
done

$ chmod 777 for.sh
$ bash for.sh aa bb cc

while loop

1. Basic grammar

while [  Conditional judgment  ]

do
    
     Program 
    
done

Case practice

​ (1) from 1 Add to 100

[email protected]:~$ touch while.sh
[email protected]:~$ vim while.sh 


#!/bin/bash
s=0
i=1
while [ $i -le 100 ]
do
    s=$[$s+$i]
    i=$[$i+1]
done

echo $s


-rw-rw-r--  1 lyh  lyh    88 Feb 15 18:33 while.sh
[email protected]:~$ bash while.sh
5050

read Read console input

1. Basic grammar

read ( Options :-p -t) ( Parameters : Variable ) 

Options :

-p: Specify the prompt when reading the value ;

-t: Specifies the time to wait while reading the value ( second ).

Parameters

Variable : Specifies the variable name of the read value

Case practice

​ (1) Tips 7 Seconds , Read the name entered by the console

[email protected]:~/test$ touch read.sh
[email protected]:~/test$ vi read.sh

#!/bin/bash

read -t 7 -p "Enter your name in 7 seconds " NAME
echo $NAME

[email protected]:~/test$ bash read.sh 
Enter your name in 7 seconds lyh
lyh

[email protected]:~/test$ bash read.sh 
Enter your name in 7 seconds 
[email protected]:~/test$ 

function

1、 System function

1. basename Basic grammar

basename [string / pathname] [suffix]

Function description :

basename The command deletes all prefixes in the path, including the last one (‘/’) character , Then display the string .

Options :

suffix For the suffix , If suffix Designated ,basename Will pathname or string Medium suffix Get rid of .

(1) Intercept this /home/lyh/test/test.txt File name of the path

[email protected]:~/test$ touch test.txt

[email protected]:~/test$ basename /home/lyh/test/test.txt 
test.txt

[email protected]:~/test$ basename /home/lyh/test/test.txt .txt
test

2. dirname Basic grammar

dirname  File absolute path 

Function description : Get file path

Remove filename from given filename with absolute path ( Non catalog part ), Then return to the rest of the path ( Part of the catalog )

[email protected]:~/test$ dirname /home/lyh/test/test.txt 
/home/lyh/test

[email protected]:~/test$ dirname test.txt 
.

2、 Custom function

Basic grammar

[ function ] funname[()]
{
    
    Action;
    [return int;]
}
funname

(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)

Addition of two numbers :

[email protected]:~/test$ touch fun.sh
[email protected]:~/test$ vi fun.sh 

#!/bin/bash

function sum()
{
    
    s=0
    s=$[ $1 + $2 ]
    return $s
}

read -p "Please input the number1: " n1;
read -p "Please input the number2: " n2;
sum $n1 $n2;
echo $s;

[email protected]:~/test$ bash fun.sh $n1 $n2
Please input the number1: 5
Please input the number2: 6
11

Shell Tools ( a key )

1、cut

cut The job of “ cut ”, Specifically, it is used to cut data in the file .cut Command to cut bytes from each line of a file 、 Characters and fields and put these bytes 、 Character and field output .

cut [ Option parameters ]  filename

 Option parameters 
-f  Column number , Extract which column 
-d  Separator , Splits columns according to the specified separator 
 explain : The default separator is tab 

cut: You must specify a set of bytes 、 A list of characters or fields

(0) Data preparation

[email protected]:~/test$ vi test.txt
[email protected]:~/test$ cat test.txt 
AA BB CC
DD,EE,FF
GG|HH|II

(1) cutting test.txt First column

[email protected]:~/test$ cut -f 1 -d " " test.txt
AA
DD,EE,FF
GG|HH|II

(2) cutting test.txt second 、 The three column

[email protected]:~/test$ cut -f 2,3 -d "," test.txt
AA BB CC
EE,FF
GG|HH|II

(3) stay test.txt Cut out in file HH

cut:  You must specify a set of bytes 、 A list of characters or fields 

[email protected]:~/test$ cat test.txt | grep "HH" | cut -f 2 -d "|"
HH

(4) Selection system PATH A variable's value , The first 2 individual “:” All paths after start :

[email protected]:~/test$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

[email protected]:~/test$ echo $PATH | cut -d : -f 3
/usr/sbin

[email protected]:~/test$ echo $PATH | cut -d : -f 3-
/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
[email protected]:~/test$ 

2、sed

sed Is a flow editor , It processes one line at a time . When dealing with , Store the currently processed rows in a temporary buffer , be called “ Mode space ”, Then use sed Command processing buffer contents , After processing , Send the contents of the buffer to the screen . Next line , This is repeated , Until the end of the file . The contents of the document have not changed , Unless you use redirected storage output .

Basic usage

sed [ Option parameters ]  ' command '  filename

 Option parameters 
-e	 Directly in command line mode sed Action editor .

 command 
a 	 newly added ,a You can use a string after , On the next line 
d	 Delete 
s	 Find and replace  


(0) Data preparation


[email protected]:~$ touch sed.txt

[email protected]:~$ vim sed.txt 
[email protected]:~$ cat sed.txt 
li lei
lei lei
xiao hong
xiao hei

(1) take “gorgeous” This word is inserted into sed.txt Second elements , Print .


[email protected]:~$ sed '2a gorgeous' sed.txt
li lei
lei lei
gorgeous
xiao hong
xiao hei

[email protected]:~$ cat sed.txt 
li lei
lei lei
xiao hong
xiao hei

 Be careful : The file hasn't changed 

(2) Delete sed.txt All files contain xiao The line of


[email protected]:~$ sed '/xiao/d' sed.txt
li lei
lei lei

[email protected]:~$ cat sed.txt 
li lei
lei lei
xiao hong
xiao hei

(3) take sed.txt In file l Replace with A


[email protected]:~$ sed 's/l/A/g' sed.txt
Ai Aei
Aei Aei
xiao hong
xiao hei

[email protected]:~$ sed 's/l/A/' sed.txt
Ai lei
Aei lei
xiao hong
xiao hei

 Be careful :‘g’ Express global, All replacement 

(4) take sed.txt The second line in the file is deleted and the l Replace with A


[email protected]:~$ sed -e '2d' -e 's/l/A/g' sed.txt 
Ai Aei
xiao hong
xiao hei

[email protected]:~$ sed '2d' 's/l/A/g' sed.txt 
sed:  Can't read  s/l/A/g:  There is no file or directory 
li lei
xiao hong
xiao hei

3、awk

A powerful text analysis tool , Read the document line by line , Slice each line with a space as the default separator , The cut part is analyzed again .


awk [ Option parameters ] 'pattern1{action1} pattern2{action2}...' filename

pattern: Express AWK What to look for in the data , It's a matching pattern 
action: A series of commands executed when a match is found 

 Option parameters 
-F   Specify the input file separator 
-v   Assign a user-defined variable 

(0) Data preparation


[email protected]:~/test$ cp /etc/passwd ./

[email protected]:~/test$ ll
 Total usage  24
drwxrwxr-x  2 lyh lyh 4096 Feb 16 00:00 ./
drwxr-xr-x 16 lyh lyh 4096 Feb 15 23:22 ../
-rw-r--r--  1 lyh lyh 2801 Feb 16 00:00 passwd

[email protected]:/etc$ cat passwd
root:x:0:0:root:/root:/bin/bash
...

(1) Search for passwd Document to root All lines at the beginning of the keyword , And output the 7 Column .

[email protected]:~/test$ awk -F : '/^root/{print $7}' passwd 
/bin/bash

(2) Search for passwd Document to root All lines at the beginning of the keyword , And output the 1 Column and the first 7 Column , In the middle to “,” Division of no. .

[email protected]:~/test$ awk -F : '/^root/{print $1","$7}' passwd 
root,/bin/bash

Be careful : Only match pattern Will be executed action

(3) Display only /etc/passwd The first and seventh columns of , Comma separated , And add column names before all rows beginshell Add on last line endshell.


[email protected]:~/test$ awk -F : 'BEGIN{print "beginshell"}{print $1","$7}END{print "endshell"}' passwd

beginshell
root,/bin/bash
daemon,/usr/sbin/nologin
...
lyh,/bin/bash
systemd-coredump,/usr/sbin/nologin
endshell

Be careful :BEGIN Execute before all data read rows ;END Execute after all data execution .

(4) take passwd Users in files id( The third column ) Increase in numerical value 1 And the output

[email protected]:~/test$ cat passwd 
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
...

[email protected]:~/test$ awk -v i=1 -F : '{print $3+i}' passwd
1
2
3
4
...

awk Built in variables for

FILENAME	 file name 
NR	 Number of records read 
NF	 The number of fields in the browsing record ( After cutting , Number of columns )

(1) Statistics passwd file name , Line number of each line , Columns per row

[email protected]:~/test$ awk -F : '{print FILENAME,NR,NF}' passwd 
passwd 1 7
passwd 2 7
passwd 3 7
passwd 4 7
passwd 5 7
passwd 6 7
passwd 7 7
passwd 8 7
passwd 9 7
passwd 10 7
passwd 11 7
passwd 12 7
passwd 13 7
passwd 14 7
...

(2) Inquire about test.txt Line number of the blank line


[email protected]:~/test$ cat test.txt 
AA BB CC
DD,EE,FF
GG|HH|II

abcd

[email protected]:~/test$ awk '/^$/{print NR}' test.txt 
4

4、sort

Sort the files , And output the sorting result standard .

sort( Options )( Parameters )

 Options :
-n	 Sort by the size of the value 
-r	 In reverse order 
-t	 Set the separator used for sorting 
-k	 Specify the columns to sort 

 Parameters : Specify the list of files to sort 

(1) according to “:” The third column after splitting is sorted in reverse order .


[email protected]:~/test$ touch sort.sh
[email protected]:~/test$ vim sort.sh
[email protected]:~/test$ cat sort.sh 
AA:40:5.4
BB:20:4.2
CC:50:2.3
DD:10:3.5
EE:30:1.6

[email protected]:~/test$ sort -t : -nr -k3 sort.sh 
AA:40:5.4
BB:20:4.2
DD:10:3.5
CC:50:2.3
EE:30:1.6

common problem :

problem 1: Use Linux Command query file1 Line number of the blank line


[email protected]:~/test$ awk '/^$/{print NR}' test.txt 
4

problem 2: Documents chengji.txt The contents are as follows :

Zhang San 40

Li Si 50

Wang Wu 60

Use Linux Command to calculate the sum of the second column and output


$ cat chengji.txt | awk -F " " '{sum+=$2} END{print sum}'
150

problem 3:Shell How to check whether a file exists in the script ? What to do if it doesn't exist ?

#!/bin/bash

if [ -f file.txt ]; then
    echo " File exists !"
else
    echo " file does not exist !"
fi
原网站

版权声明
本文为[_ seven seven]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270547234958.html