Shell script basic tutorial, get started quickly

The first shell script: helloworld

The script starts with #!/bin/bash (specify parser)

Next create a Shell script that outputs helloworld

  1. touch hello.sh

  2. write command

    #!/bin/bash

    echo “helloworld”

  3. Execute after saving, the figure is divided into absolute path and relative path execution, sh bash has the same function, except that sh points to bash, which is a soft link, and finally calls bash; directly executing in the root directory requires granting script permissions

insert image description here

The first execution method is essentially that the bash parser helps you execute the script, so the script itself does not need execution permission. The second execution method is essentially that the script needs to be executed by itself, so execution permission is required.

Second Shell Script: Multi-Command Processing

Create a demo.txt in the shell directory, and add "I like drinking Coke" to the demo.txt file.

#!/bin/bash
touch demo.txt
echo "I like drinking Coke" >> demo.txt

insert image description here

variables in the shell

System and custom variables

Commonly used system variables: HOME, HOME,HOMEPWD、 S H E L L 、 SHELL、 S H E LL , USER, etc. are convenient for writing operations in files.

insert image description here

1. basic grammar

​ (1) Define variables: variable = value

​ (2) Undo variable: unset variable

​ (3) Declare static variables: readonly variables, note: cannot unset

2. Variable Definition Rules

​ (1) The variable name can consist of letters, numbers and underscores, but cannot start with a number. It is recommended to capitalize the environment variable name.

​ (2) There can be no spaces on both sides of the equal sign

​ (3) In bash, the default type of variables is a string type, which cannot directly perform numerical operations.

​ (4) If the value of the variable has spaces, it needs to be enclosed in double quotes or single quotes.

​ (5) The variable can be promoted to a global environment variable, which can be used by other shell programs: export variable name

sxh@learn-basis:shell$ A=4				//定义变量A
sxh@learn-basis:shell$ echo $A
4
sxh@learn-basis:shell$ A=9				//给变量A重新赋值
sxh@learn-basis:shell$ echo $A
9
sxh@learn-basis:shell$ unset A				//撤销变量A
sxh@learn-basis:shell$ echo $A

sxh@learn-basis:shell$ readonly B=2				//声明静态的变量B=2,不能unset
sxh@learn-basis:shell$ echo $B
2
sxh@learn-basis:shell$ unset B
bash: unset: B:无法取消设定: 只读 variable
sxh@learn-basis:shell$ C=1+2				//在bash中,变量默认类型都是字符串类型,无法直接进行数值运算
sxh@learn-basis:shell$ echo $C
1+2
sxh@learn-basis:shell$ D=I love you			//变量的值如果有空格,需要使用双引号或单引号括起来
/*error
Command 'love' not found, but can be installed with:
sudo snap install love  # version 11.2+pkg-d332, or
sudo apt  install love  # version 11.3-1
See 'snap info love' for additional versions.
*/
sxh@learn-basis:shell$ D="I love you"
sxh@learn-basis:shell$ echo $D
I love you
sxh@learn-basis:shell$ vi hello.sh
	写入#!/bin/bash
	echo "hello sxh"
	echo $C
sxh@learn-basis:shell$ ./hello.sh 
hello sxh
									//发现并没有打印输出变量C的值。
sxh@learn-basis:shell$ export C		//把变量提升为全局环境变量,可供其他Shell程序使用
sxh@learn-basis:shell$ ./hello.sh 
hello sxh
1+2				//success

special variable

  1. ​ $n (Function description: n is a number, $0 represents the name of the script, $1- 9 represents the first to ninth parameters, more than ten parameters, and more than ten parameters need to be enclosed in braces, such as 9 represents the first to ninth parameters The ninth parameter, more than ten parameters, and more than ten parameters need to be enclosed in braces, such as9 stands for the first to ninth parameters, and more than ten parameters need to be enclosed in braces, such as {10})

new file write

#!/bin/bash

echo “$0 $1 $2”

insert image description here

Output the script file name, the values ​​of input parameter 1 and input parameter 2, parameter 3 is no longer output

  1. ​ $# (Function description: Get the number of all input parameters, often used in loops)

Edit file write echo $#

Get the number of input parameters

insert image description here

  1. ∗ (Function description: This variable represents all the parameters in the command line, * (Function description: This variable represents all the parameters in the command line,(Function description: this variable represents all the parameters in the command line, * treat all parameters as a whole)

    @ (Function description: This variable also represents all parameters in the command line, but @ (Function description: This variable also represents all parameters in the command line, but@ (Function description: This variable also represents all parameters in the command line, but @ treats each parameter differently)

    Both are to print all the parameters entered

  2. $? (Function description: the return status of the last executed command. If the value of this variable is 0, it proves that the previous command was executed correctly; if the value of this variable is not 0 (the specific number is determined by the command itself), then Prove that the previous command was executed incorrectly)

sxh@learn-basis:shell$ ./para.sh a b c 
./para.sh a b
3
a b c
a b c
sxh@learn-basis:shell$ echo $?
0    //返回0表示正确

operator

(1) " ( ( expression) ) " or " ( ( expression)) " or "(( expression )) or " [expression]"

(2) expr + , - , *, /, % add, subtract, multiply, divide, take remainder

​Note : There must be spaces between expr operators

insert image description here

`expr 3 + 2` 先运算加法   \*再运算乘法

conditional judgment

  1. basic grammar

[ condition ] (note that there must be spaces before and after condition)

Note: The condition is true if it is not empty, [ atguigu ] returns true, and [] returns false.

  1. Common Judgment Conditions

(1) Comparison between two integers

= string comparison

-lt less than (less than) -le less than or equal to (less equal)

-eq equal to (equal) -gt greater than (greater than)

-ge greater than or equal to (greater equal) -ne not equal to (Not equal)

(2) Judge according to file permissions

-r has read permission (read) -w has write permission (write)

-x has permission to execute (execute)

(3) Judging by file type

-f file exists and is a regular file (file)

-e file exists (existence) -d file exists and is a directory (directory)

(4) Multi-condition judgment (&& indicates that the next command will be executed only when the previous command is successfully executed, and || indicates that the next command will be executed only after the previous command fails to execute)

insert image description here

process control

if judgment

grammar:

if [conditional judgment expression];then

program

fi

or

if [ conditional judgment expression ]

then

​ program

fi

​ Notes:

(1) [Conditional judgment formula], there must be a space between the square brackets and the conditional judgment formula

(2) There must be a space after if

demo: Input a number, if it is 1, output I like drinking Coke, if it is 2, output I like to drink Sprite, if it is other, output nothing.

#!/bin/bash

if [ $1 -eq "1" ];then
    echo "I like drinking Coke"
elif [ $1 -eq "2" ]
then 
    echo "I like to drink Sprite"
fi

insert image description here

case statement

grammar:

case $ variable name in

"value1")

​ If the value of the variable is equal to the value 1, execute program 1

​ ;;

"value2")

​ If the value of the variable is equal to the value 2, execute program 2

​ ;;

...omit other branches...

*)

​ If the value of the variable is not the above value, execute this program

​ ;;

esac

Precautions:

  1. The case line must end with the word "in", and each pattern match must end with a closing bracket ")".
  2. The double semicolon " ;; " indicates the end of the command sequence, which is equivalent to break in java.
  3. The last "*)" indicates the default mode, which is equivalent to default in java.

demo: Input a number, if it is 1, output I like drinking Coke, if it is 2, output I like to drink Sprite, if it is other, output nothing.

#!/bin/bash

case $1 in 
1)
    echo "I like drinking Coke"
;;
2)
    echo "I like to drink Sprite"
;;
*)
    echo "nothing"
;;
esac

insert image description here

for loop

Basic syntax 1:

​ for ((initial value; loop control condition; variable change))

do

​ program

done

demo: add from 1 to 100

#!/bin/bash

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

insert image description here

Basic syntax 2:

for variable in value1 value2 value3...

do

​ program

done

demo: print all input parameters

sxh@learn-basis:shell$ touch for2.sh
sxh@learn-basis:shell$ vi for2.sh 
#!/bin/bash

for i in $*
do
    echo "this is a char $i"
done


sxh@learn-basis:shell$ sh for2.sh a
this is a char a
sxh@learn-basis:shell$ sh for2.sh a b
this is a char a
this is a char b
sxh@learn-basis:shell$ sh for2.sh a b c
this is a char a
this is a char b
this is a char c

Compare ∗ with * andand @ difference

(a) ∗ and * andBoth ∗ and @ represent all parameters passed to the function or script, and when they are not enclosed by double quotes "", they all start with $12 ... 2 ...2... output all arguments in the form of n.

sxh@learn-basis:shell$ vi for2.sh 
#!/bin/bash

for i in $*
do
    echo "this is a char $i"
done

for j in $@
do 
    echo "this is a char $j"
done 

sxh@learn-basis:shell$ sh for2.sh a
this is a char a
this is a char a
sxh@learn-basis:shell$ sh for2.sh a b
this is a char a
this is a char b
this is a char a
this is a char b
sxh@learn-basis:shell$ sh for2.sh a b c
this is a char a
this is a char b
this is a char c
this is a char a
this is a char b
this is a char c

(b) When they are enclosed by double quotes "", "$*" will take all the parameters as a whole to "$1 2 ... 2 ...2... n" to output all parameters; "$@" will separate each parameter to "$1" "2 "... "2"..."2”Output all parameters in the form of " n".

#!/bin/bash

for i in "$*"
do
    echo "this is a char $i"
done

for j in "$@"
do 
    echo "this is a char $j"
done 

insert image description here

while loop

Basic syntax:

while [ conditional judgment expression ]

do

​ program

done

sxh@learn-basis:shell$ touch while.sh
sxh@learn-basis:shell$ vi while.sh 
sxh@learn-basis:shell$ cat while.sh 
#!/bin/bash
s=0
i=1
while [ $i -le 100 ]
do
        s=$[$s+$i]
        i=$[$i+1]
done
echo $s
sxh@learn-basis:shell$ sh while.sh 

read reads console input

Basic syntax:

​ read(options)(parameters)

​ Options:

-p: Specify the prompt when reading the value;

-t: Specifies the time (in seconds) to wait when reading a value.

parameter

​ Variable: Specify the variable name to read the value

demo: within 5 seconds of prompting, read the name entered by the console

sxh@learn-basis:shell$ touch read.sh
sxh@learn-basis:shell$ vi read.sh 
sxh@learn-basis:shell$ cat read.sh 
#!/bin/bash

read -t 5 -p "Enter your name in 5 seconds" NAME

echo $NAME

sxh@learn-basis:shell$ sh read.sh 
read.sh: 3: read: Illegal option -t

sxh@learn-basis:shell$ bash read.sh 
Enter your name in 5 secondsaaaa
aaaa
sxh@learn-basis:shell$ 

For the error that appears:

Running on ubuntu for -s -t parameters

bash read.sh and ./read.sh can be executed correctly, but sh read.sh cannot be executed correctly and an error is reported

read.sh: 4: read: Illegal option -t

The same is true for the parameter option -n

function

system function

basename basic syntax:

basename [string / pathname] [suffix] (function description: the basename command will delete all prefixes including the last ('/') character, and then display the string.

options:

suffix is ​​the suffix, if suffix is ​​specified, basename will remove the suffix in pathname or string.

dirname basic syntax:

dirname file absolute path (function description: remove the file name (non-directory part) from the given file name containing the absolute path, and then return the remaining path (directory part))

insert image description here

custom function

1. basic grammar

[ function ] funname[()]

{

​ Action;

​ [return int;]

}

funname

2. Skills

​ (1) The function must be declared before calling the function, and the shell script is run line by line. Does not compile first like other languages.

​ (2) The return value of the function can only be obtained through the $? system variable, which can be displayed and added: return return, if not added, the result of the last command will be used as the return value. return followed by the value n (0-255)

demo: Calculate the sum of two input parameters

insert image description here

ShellTools

cut

The job of cut is to "cut", specifically, it is responsible for cutting data in the file. The cut command cuts bytes, characters, and fields from each line of a file and outputs them.

1. Basic usage

cut [option parameter] filename

Description: The default delimiter is tab

2. Option parameter description

option parameter Function
-f Column number, which column to extract
-d Delimiter, split columns according to the specified delimiter
sxh@learn-basis:shell$ touch cut.txt
sxh@learn-basis:shell$ vi cut.txt 
sxh@learn-basis:shell$ cat cut.txt 
dong shen
guan zhen
wo  wo
lai  lai
le  le
sxh@learn-basis:shell$ cut -d " " -f 1 cut.txt 
dong
guan
wo
lai
le
sxh@learn-basis:shell$ cut -d " " -f 2,3 cut.txt 
shen
zhen
 wo
 lai
 le
sxh@learn-basis:shell$ cat cut.txt | grep "guan" | cut -d " " -f 1
guan
//这里是过滤文件找到guan那一行,然后对这一行进行cut

Next, look at the cut system variable
insert image description here

sed

sed is a stream editor that processes content one line at a time. When processing, the currently processed line is stored in a temporary buffer, which is called "pattern space", and then the content in the buffer is processed with the sed command. After the processing is completed, the content of the buffer is sent to the screen. Then process the next line, and repeat until the end of the file. The file contents are not changed unless you use redirected storage output.

  1. basic usage

sed [options] 'command' filename

  1. Option parameter description
option parameter Function
-e Edit sed actions directly in command line mode.
  1. Command function description
Order Functional description
a Added, a string can be connected after a, and it will appear on the next line
d delete
s find and replace
sxh@learn-basis:shell$ touch sed.txt
sxh@learn-basis:shell$ vi sed.txt 
sxh@learn-basis:shell$ cat sed.txt //数据准备
dong shen
guan zhen
wo  wo
lai  lai

le  le
sxh@learn-basis:shell$ sed '2a hi hao' sed.txt 
dong shen			//将“hi hao”这个单词插入到sed.txt第二行下,打印。
guan zhen
hi hao
wo  wo
lai  lai

le  le
sxh@learn-basis:shell$ cat sed.txt  //文件不会有变化,只是输出有变化
dong shen
guan zhen
wo  wo
lai  lai

le  le
sxh@learn-basis:shell$ sed '/wo/d' sed.txt //删除sed.txt文件所有包含wo的行
dong shen
guan zhen
lai  lai

le  le
sxh@learn-basis:shell$ sed 's/wo/ni/g' sed.txt   //将sed.txt文件中wo替换为ni
dong shen
guan zhen
ni  ni
lai  lai

le  le
sxh@learn-basis:shell$ sed -e '2d' -e 's/wo/ni/g' sed.txt 
dong shen    //将sed.txt文件中的第二行删除并将wo替换为ni
ni  ni
lai  lai

le  le
sxh@learn-basis:shell$ 

awk

A powerful text analysis tool that reads files line by line, slices each line with spaces as the default delimiter, and then analyzes and processes the cut parts.

  1. basic usage

awk [option parameter] 'pattern1{action1} pattern2{action2}…' filename

pattern: Indicates what AWK is looking for in the data, which is the matching pattern

action: A sequence of commands to execute when a match is found

  1. Option parameter description
option parameter Function
-F Specify input file fold delimiter
-v Assign a value to a user-defined variable

sort

The sort command is very useful in Linux, it sorts files and outputs the sorted results to standard output.

  1. ​ Basic grammar

sort(option)(argument)

options illustrate
-n Sort by numerical value
-r sort in reverse order
-t Set the delimiter character used when sorting
-k Specify the column to be sorted

Guess you like

Origin blog.csdn.net/qq_44333320/article/details/126602266