当前位置:网站首页>Shell programming basics

Shell programming basics

2022-07-07 03:13:00 A-L-Kun

Shell Programming

One 、 summary

1、 shell A term is used to explain

kernel

  • linux The kernel is mainly for dealing with hardware

shell

  • command interpreter
  • shell It's a use. C A program written in a language , It is used by users linux The bridge ,shell It's a command language , Another programming language
  • shell It's an application , This application provides an interface , Users access the services of the operating system kernel through this interface

Shell It's a use. C A program written in a language , It is used by users Linux The bridge .Shell It's a command language , Another programming language .

Shell It's an application , This application provides an interface , Users access the services of the operating system kernel through this interface .

Ken Thompson Of sh It's the first one Unix Shell,Windows Explorer It's a typical graphic interface Shell.

2、 The first script

#! Statement : Tell the system that the program specified by the path is to interpret the script file shell Program

#!/usr/bin/bash
echo -e "hello world!\n"

Script execution :

#  Mode one 
bash hello.sh
sh hello.sh  # sh  yes  bash  The soft links 

#  Mode two 
chmod u+x hello.sh  #  Make the file have permission to execute 
./hello.sh  #  Run the file 

#  Mode three 
source hello.sh  #  Load the script file 

The difference between starting methods :

  • Mode 1 and mode 2 will open a new bash, Different bash Variables in cannot be shared
  • The third way is in the same bash What's going on inside

export: You can pass the variables of the current process to the child process to use

  • To configure profile When , All variables must be preceded by export

Two 、 Basic introduction

1、 Variable

When defining variables , Variable name without dollar sign

  • Only English letters can be used for naming , Numbers and underscores , The first character cannot begin with a number
  • No spaces in between , You can use underscores
  • You can't use punctuation
  • Out of commission bash Keywords in it ( You can use help Command to view reserved keywords )

The type of variable

  • local variable

    • Local variables are defined in scripts or commands , At present only shell Valid in instance , other shell Started program cannot access local variables
  • environment variable

    • All procedures , Include shell Program started , Can access environment variables , Some programs need environment variables to ensure their normal operation
    Linux Common environment variables in are :
    
        1.PATH: Specify the search path for the command 
    
        2.HOME: Specify the user's home working directory ( That is, the user logs in to Linux Time in system , The default directory )
    
        3.HISTSIZE: It refers to the number of historical command records saved .
    
        4.LOGNAME: The login name of the current user .
    
        5.HOSTNAME: The name of the host , Many applications use host names , Usually from this environment variable .
    
        6.SHELL: It refers to what kind of Shell.
    
        7.LANG/LANGUGE: Language related environment variables , Users with multiple languages can modify this environment variable .
    
        8.MAIL: It refers to the mail storage directory of the current user .
    
        9.PS1: Command basic prompt , about root User is #, For ordinary users $.
    
        10.PS2: It's a secondary prompt , The default is “>”.
    
  • shell Variable

    • shell Variables are derived from shell Special variables for program settings ,shell Some of the variables are environment variables , Some are environment variables
#!/bin/bash

name="lihua"  #  local variable 
printf "%s\n" ${name}  # ${name} = $name, They are all calls to variables 

export name_="zhansan"  #  environment variable 

readonly name  #  A read-only variable 

unset name  #  Delete variables 

2、 character string

The string is shell The most common and useful data types in , Strings can be in single quotes , You can also use double quotes , You can also use no quotes

Single quotation marks :

  • Any string in single quotation marks will be output as is , Variables in a single quoted string are invalid
  • A single single quotation mark... Cannot appear in a single quotation mark string , But in pairs , Used as character splicing

Double quotes :

  • Double quotes can have variables
  • Escape characters can appear in double quotation marks
#!/bin/bash

#  Declaration string 
str1='hello'

#  String splicing -- Single quotation marks 
pwd='123'
pwd1='hello, '${pwd}'!'  # -> hello, 123
pwd2='hello, ${pwd}!'  # -> hello, ${pwd} 
pwd3="hello, ${pwd}!"  # -> hello, 123

#  String length 
email="[email protected]"
echo ${
    #email}  #  Returns the length of the string 
echo ${email:1:4}  #  String truncation 

3、 Array

bash Support for arrays , Multidimensional arrays are not supported , And there's no limit to the size of the array

The element subscript of the array is 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 , Array elements are separated by spaces 
 Array name =( value 1  value 2 ...  value n)

#!/usr/bin/bash
names=("lihua", "zhansan", "lishi")

#  Reading data  `$( Array [ Subscript ])`
name=${names[0]}
#  Use  @  The symbol can get all the elements in the array 
echo ${names[@]}

#  Gets the length of the array 
len1=${
    #names[@]}  #  The two effects are the same 
len2=${
    #names[*]}
echo -e "len1=${len1}"
echo -e "len2=${len2}"

4、 notes

With # The first line is the comment , Will be ignored by the interpreter

Add one... To each line # No. can realize multi line annotation

#  This is after a single line comment , The compiler will not execute this code 

# Multiple lines 
# notes 
echo "hello world!"
:<<EOF  This is also a multi line comment ! EOF

:<<!
 This is also a multi line comment !
!

5、 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 parameter tables passed to the script
$* Display all the parameters passed to the script in a single string
$$ The current process the script runs ID Hao
$! The last process running in the background ID Number
$? Display the last command exit status ,0 No mistakes , Any other value indicates an error
$0 File name of execution
#!/bin/bash

printf "Shell  Passed parameter instance !\n";
printf " File name of execution :$0\n";
printf " The first parameter is zero :$1\n";
printf " The second parameter is :$2\n";

3、 ... and 、 Operator

1、 Arithmetic operator

Operator explain give an example
+ Add expr $a + $b The result is 30.
- Subtraction expr $a - $b The result is -10.
* Multiplication expr $a \* $b The result is 200.
/ division expr $b / $a The result is 2.
% Remainder expr $b % $a The result is 0.
= assignment a=$b Put variables b The value is assigned to a.
== equal . Used to compare two numbers , Same returns true.[ $a == $b ] return false.
!= It's not equal . Used to compare two numbers , If not, return to true.[ $a != $b ] return true.
+ - * / % = == !=

2、 Relational operator

Operator 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.
-eq -> ==  # equals
-ne -> !=  # not equals
-gt -> >  # great than
-lt -> <  # less than 
-ge -> >=  # great equal
-le -> <=  # less equal

3、 Boolean operator

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.
-a # and  And 
-o # or  or 
!  # not  Not 

4、 Logical operators

Operator explain give an example
&& Logical AND[[ $a -lt 100 && $b -gt 100 ]] return false
|| Logical OR`[[ $a -lt 100
&&  #  Short circuit and 
||  #  Short circuit or 

5、 String operators

Parameters explain
= Equal is true
!= Inequality is true
-z character string A zero length string is true
-n character string True if the length of the string is not zero
#!/bin/bash

a="abc"
b="efg"

if [ $a == $b ] then
	echo "$a = $b : a be equal to b"
else
	echo "$a = $b : a It's not equal to b"
fi

if [ $a != $b ] then
	echo "$a = $b : a It's not equal to b"
else
	echo "$a = $b : a be equal to b"
fi

if [ -z $a ] then
	echo "-z $a :  String length is 0"
else
	echo "-z $a :  String length is not 0"
fi

if [ -n $a ] then
	echo "-n $a :  String length is not 0"
else
	echo "-n $a :  String length is 0"
fi

if [ $a ] then
	echo "$a :  String is not empty "
else
	echo "$a :  The string is empty "
fi

6、 File test operators

Parameters explain
-e file name True if the file exists
-r file name True if the file exists and is readable
-w file name True if the file exists and is writable
-x file name True if the file exists and is executable
-s file name True if the file exists and has at least one character
-d file name True if the file exists and is a directory
-f file name True if the file exists and is a normal file
-c file name True if the file exists and is a special character file
-b file name True if the file exists and is a block special file
#!/usr/bin/bash

file="/home/kun/a.py"

if [ -r $file ] then
	echo " Documents are readable "
else 
	echo " The file is unreadable "
fi

if [ -w $file ] then
	echo " Documents can be written "
else 
	echo " The document is not writable "
fi

if [ -x $file ] then
	echo " The document is executable "
else 
	echo " The file is not executable "
fi

if [ -f $file ] then
	echo " The file is a normal file "
else 
	echo " Documents are special documents "
fi

if [ -d $file ] then
	echo " A file is a directory "
else 
	echo " The file is not a directory "
fi

if [ -s $file ] then
	echo " The file is not empty "
else 
	echo " The file is empty "
fi

if [ -e $file ] then
	echo " File exists "
else 
	echo " file does not exist "
fi

7、 test

Use test To determine whether the conditions are true

#!/usr/bin/bash

name1="lihua"
name2="lihua"

if test ${name1} == ${name2}
then
        echo " The two names are equal "
fi

Four 、 Process control

1、 Branch statement

1.1 if

if condiction1
then 
	command1
elif condiction2
then
	command2
else 
	command3
fi

example :

#!/bin/bash

a=10
b=20
if [ $a == $b ]
then 
	echo "a = b"
elif test $a -lt $b
then 
	echo "a < b"
else
	echo "a > b"
fi

1.2 case

case expression in
    pattern1)
        statement1
        ;;
    pattern2)
        statement2
        ;;
    pattern3)
        statement3
        ;;
    …
    *)
        statementn
esac

example :

#!/bin/bash

read -p "Enter a number: " num
case $num in
	1) echo " You entered 1"
	;;
	2) echo " You have entered 2"
    ;;
    3|4|5echo " You have entered 3~5"
    ;;
    *) echo " You entered except 1 and 2 Other numbers "
    ;;
esac

2、 Loop statement

2.1 for

#  grammar 1:C Language style 
for((exp1; exp2; exp3))
do
    statements
done

#  example 
for ((i=1; i<100; i++))
do 
	echo $i
done

#  grammar 2;python style 
for variable in value_list -》  It can also be a value range  {
    start..end}
do
    statements
done

#  Example 
for n in 1 2 3 4 5 6
do
    echo $n
     ((sum+=n))
done
echo "The sum is "$sum

Use cases :

#!/bin/bash

for i in `ls /bin/`  #  Traverse ls The result returned , Use $(ls) It's the same 
do
        echo "The filepath is $i"
done

echo "over"

2.2 while

while Loop is used to execute a series of commands continuously , Also used to read data from the input file ; Commands are usually test conditions

while condition
do 
	command
	if condition1
	then 
		break  #  Exit loop 
	if condition2
	then 
		continue  #  Break this cycle 
done

5、 ... and 、 function

1、 brief introduction

shell You can define functions , And then again shell You can call... In the script

Sure function func() Definition , It can also be direct func() Definition , Without any parameters

Parameter return , Can display plus :return return , Results will be run with the last command , As return value ,return Heel value n

2、 Definition

func() {
    
	command
	return ...
}

func
ret=$?  #  Use $? To get the return value of the function 

3、 Use cases

#!/bin/bash
#  Function definition 
function firstFunc() {
    
        echo -e " The function starts executing \nhello world!\n The function ends execution "
}
#  There are function return values 
secondFunc() {
    
        echo " The function of this function is to add two input numbers "
        read -p " Please enter the first number :" num1
        read -p " Please enter the second number :" num2
        return $(($num1+$num2))
}
#  Calls to functions with parameters 
thirdFunc() {
    
        echo -e "--------------------\n Calls to functions with parameters "
        echo " The first parameter passed in by the function is :$1"
        echo " The second parameter passed in by the function is :$2"
		echo " The total parameters passed in are :$# individual "
}

#  Function call 
firstFunc
echo -e " Start executing the second function \n------------------------------\n"
secondFunc
#  The return value of the function call passes after the function is called $?( The last returned result ) To obtain a 
ret=$?
echo " The result of adding the second function is $ret"
thirdFunc  The first parameter   The second parameter 

6、 ... and 、 other

1、 Redirect

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 .

2、 File contains

Like any other language ,Shell You can also include external scripts . This can easily encapsulate some common code as a separate file .

Shell The file contains the following syntax format :

. filename   #  Note the number (.) There is a space between the file name and the file name 

 or 

source filename  

These two methods have the same effect

7、 ... and 、 System task settings

1、 System startup process

Start the computer's hardware [BIOS]

  • Read time
  • Select the corresponding startup mode

If it is Linux System , Will go to /boot Catalog , Boot the system up

The computer system starts up , Read initialization profile

  • vim /etc/inittab

  • Startup time , It controls the running level of the computer

    • Operation level 0: System shutdown status , The default operation level of the system should not be set to 0, Otherwise it will not start properly ;
    • Operation level 1: Single user working state , have root jurisdiction , For system maintenance , No remote login ;
    • Operation level 2: Multi user status ( No, NFS, Can't connect to the Internet );
    • Operation level 3: Full multi-user state ( Yes NFS, Can be networked ), Log in and enter the console command line mode ;
    • Operation level 4: The system is not in use , Retain ;
    • Operation level 5:X11 Console , Log in and enter the figure GUI Pattern ;
    • Operation level 6: The system shuts down and restarts normally , The default run level cannot be set to 6, Otherwise it will not start properly ;
  • The default is level 3, Start the corresponding services and components at level three

Start to boot public components or services by default

  • vim /etc/rc.d/init.d
  • You can move script files to this directory , Start up automatically

Start loading the corresponding runserver Service for

  • vim /etc/rc.d/rc3.d
    • K: Services that need to be shut down when shutting down
    • S: Services that need to be started when starting
    • Numbers represent the order of opening or closing
    • All files are soft links , The address of the link is /etc/init.d

When startup is complete , All services are also loaded

2、 system service

We can use chkconfig Command to view the services of the current virtual machine

By checking, we can know that different levels correspond to each service, and determine that this startup is self starting

After starting up , We need to use systemctl The command controls the opening or closing of the service

3、 Boot up

3.1 rc.local

  1. First create the folder where the script is stored
    • mkdir -p /usr/local/scripts
  2. Create script file in folder
    • vim hello.sh
  3. Give permission to execute
    • chmod a+x hello.sh
  4. Go to /etc/rc.d/rc.local The absolute path of the script added to the file
    • echo "/usr/local/scripts/hello.sh" >> /etc/rc.d/rc.local
  5. chmod a+x /etc/rc.d/rc.local : to rc.local Add permission to execute

3.2 chkconfig

  1. Create a startup and self startup script file
    • vim hello.sh
  2. Give permission to execute
    • chmod a+x hello.sh
  3. Copy the script file to /etc/init.d Under the table of contents
    • cp hello.sh /etc/init.d/
  4. Add to service
    • chkconfig --add /etc/init.d/hello.sh
  5. Restart the server
    • reboot

4、 Timing task

  1. In the system service center ,crond Responsible for periodic tasks

    • systemctl status crond.service
  2. Add tasks , Edit the task list of the current user

    • crontab -e
  3. Editing task

    grammar :

    */1 * * * * sh /usr/local/scripts/hello.sh
     branch   when   Japan   month   Zhou   command 
     branch :1~59
     when :1~23,0 Express 0 spot 
     Japan :1~31
     month :1~12
     Zhou :0~6  0 Sunday 
     command : Indicates the command to run 
    

    *: Every time you use * perhaps */1 Express , Every minute , Every hour

    -: Indicates the interval , It's a range

    ,: It's a split period , Indicates discontinuity

    /n: To represent a division , It can be seen as division ,*/n each n Once per minute

原网站

版权声明
本文为[A-L-Kun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207061932527679.html