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

Shell script

2022-07-05 08:16:00 chen_ bx

Preface

Notes of this article refer to Qianfeng education
b Stop video :Linux A full set of video tutorials for advanced programming ( Easy to understand )(1P-17P)

shell grammar

shell Definition and execution of script

  1. The definition begins with :#!/bin/bash
    #! Used to declare what the script is made of shell explain , Otherwise use the default shell

  2. Single "#" The number represents the current line of the comment

  3. perform :

    chmod + x test.sh ./test.sh Execute after adding executable permission
    bash test.sh Directly specify the use of bash explain test.sh
    . test.sh(source test.sh) With the current shell Read interpretation test.sh
    The first method requires modifying the executable permissions
    The second and third do not need

  4. The three ways of executing scripts are different :
    ./ and bash The execution process is basically the same , The latter clearly specifies bash The interpreter executes the script , Script #! The specified interpreter does not work . The former first detects #!, Use #! designated shell, If you don't use the default shell
    use ./ and bash To execute will start a new... In the background shell To execute the script
    use . Executing the script will not start a new shell, Directly from the current shell To explain the execution script .

Example
demo1.sh Code

#!/bin/bash
# #! Used to specify the current script file shell Interpreter type , If you don't write , Use the default shell

#shell The script is shell An ordered collection of commands , The code is made up of commands 

ls

pwd

echo "hello"

Running results
 Insert picture description here

Shell Variable

Custom variable

shell There is no data type in No, int char…, direct Variable =value
Such as :i = 50

Reference variables
$ Variable name
Such as :i=$num Put variables num The value of is paid to the variable i

Show variable
Use echo The command can display the value of a single variable
Such as :echo $num

Clear variables
Use unset Command to clear variables
Such as :unset varname

Example 1
demo2.sh Code

#!/bin/bash

num=50

i=$num


echo $num
echo $i 

unset num
echo "***********delete************"
echo $num

Running results
 Insert picture description here


The following error is reported ( Command not found ) as a result of

num=50
i=$num

Spaces appear on both sides of the equal sign between variables and values
shell Remember not to add spaces during script assignment
 Insert picture description here

Other uses of variables :
read string( Type on scanf)
Enter a string variable from the keyboard string

readonly var=100

Define a read-only variable , Can only be initialized at definition time , It can't be changed in the future , Cannot be cleared .

export var=300

Use export Variable of description , Will be exported as environment variables , Other shell All can use
Be careful : You must use source 2_var.sh It will take effect

matters needing attention

  1. Variable names can only contain English letters and underscores , Cannot start with a number
    1_num=10 error
    num_1=20 correct
  2. The equal sign cannot be directly followed by a space character , If the variable itself contains spaces , Then the whole string should be in double quotation marks 、 Or enclosed in single quotation marks ; Special characters in double quotation marks can retain variable characteristics , However, special characters in single quotation marks are only general characters .
name=aa bb // error 
name="aa bb" // correct 
echo "$name is me" // Output :aa bb is me
echo '$name is me' // Output :$name is me

environment variable

shell At the beginning of execution, some variables related to the working environment of the system have been defined , We are shell Can be used directly in $name quote
Definition :
Generally in ~/.bashrc or /etc/profile In file ( Script automatically called by the system ) Use export Set up , Allow users to change later

VARNAME=value 
export VARNAME

Traditionally , All environment variables are capitalized
Show environment variables
Use env Command to view all environment variables .
Clear environment variables
Use unset Command to clear environment variables
Common environment variables :

HOME: The full pathname used to save the registration Directory .
PATH: Used to save colon separated directory pathnames ,shell  Will press  PATH  Search these directories in the order given in the variable , The first executable found that matches the command name will be executed .
 PATH=$HOME/bin:/bin:/usr/bin;export PATH 
HOSTNAME: Host name 
SHELL: default  shell  Command parser 
LOGNAME: This variable holds the login name 
PWD: Absolute pathname of the current working directory 
......

Environment variables set under the terminal , Only temporarily valid , If you open another terminal or restart it , The environment variable will disappear . If you want to set permanently saved environment variables , Can be found in ~/.bashrc or /etc/profile In file Add

VARNAME=value 
export VARNAME

Example 2

demo3.sh Code

#!/bin/bash
echo "You are welcome to use bash"
echo "Current work dirctory is $PWD"
echo "the host name is $HOSTNAME"
echo "your home dir $HOME"
echo "Your shell is $SHELL"

Running results
 Insert picture description here

Preset variables

$#: Pass to  shell  Number of script parameters 
$*: Pass to  shell  Contents of script parameters 
$1$2$3...、$9: Parameters passed to the script when it runs , Space off 
$?: The state returned after command execution 
"$?" Used to check whether the last command is executed correctly ( stay  Linux  in , The exit status of the command is  0  Indicates that the command is executed correctly , Anything that is not  0  Value indicates an error in the command )
$0: The name of the currently executing process 
$$: The process number of the current process 
"$$" The most common use of variables is as the name of temporary files to ensure that temporary files are not repeated 

Example
demo4.sh

#!/bin/bash
echo "your shell script name is $0"
echo "the params of your input is $*"
echo "the num of your input params is $#"
echo "the params is $1 $2 $3 $4"
ls
echo "the cmd state is $?"
cd /root
echo "the cmd state is $?"
echo "process id is $$"

Running results
 Insert picture description here
 Insert picture description here

Special usage of script variables :"" `` ’ \ () {}

“”( Double quotes ): The contained variables will be interpreted
‘’( Single quotation marks ): The included variables will be interpreted as strings
``( Number keys 1 The back quote on the left ): The contents in the back quotation marks are used as system commands , And execute its contents , You can replace the output with a variable equivalent to $()

```powershell $ echo "today is `date` "
today is 2012  year  07  month  29  Sunday, Sunday  12:55:21 CST
\  Escape character :
 Same as  c  Language  \n \t \r \a  etc.  echo  The command needs to add -e  escape 
( Command sequence ):
 Yuko  shell  To complete , Does not affect the present  shell  The variables in the 
{
      Command sequence  }:
 At present  shell  In the implementation of , Will affect the current variable 

Example
demo5.sh Code

#!/bin/bash
name=teacher
string1="good moring $name"
string2='good moring $name'
echo $string1
echo $string2
echo "today is `date` "
echo 'today is `date` '
echo -e "this \n is\ta\ntest"
( name=student;echo "1 $name" )
echo 1:$name
{
     name=student; echo "2 $name"; }
echo 2:$name

Running results

 Insert picture description here

Conditional test statements

Writing shell Script time , The problem we often encounter is to judge whether the strings are equal , You may also need to check the file status or enter
Conduct digital test , Only after these tests are completed can we do the next step
test command : Used to test string 、 File status and numbers
test There are two formats for commands :

 test condition  or  [ condition ]

When using square brackets , Pay attention to adding spaces on both sides of the condition
shell The condition test in the script is as follows :
File test 、 String test 、 Digital test 、 Composite test
Test statements are generally used in conjunction with the conditional statements described later

File test

By file type

-e  file name   Does the file exist 
-s  file name   Whether it is not empty 
-b  file name   Block device file 
-c  file name   Character device file 
-d  file name   Directory file 
-f  file name   Ordinary documents 
-L  file name   Soft link file 
-S  file name   Socket file 
-p  file name   Pipeline files 

According to file permissions

-r  file name   Can be read 
-w  file name   Can write 
-x  file name   Executable 

Comparison between two files

 file 1 -nt  file 2  file 1 Whether the modification time of the file is longer than 2 new 
 file 1 -ot  file 2  file 1 Whether the modification time of the file is longer than 2 used 
 file 1 -ef  file 2  Two files inode Whether the node number is the same , Used to determine whether it is a hard link 

Example
demo6.sh Code
$? Return execution result 0 To be right Not 0 For a mistake

#! /bin/bash

echo "please input a filename >>> "
read FILE

test -e $FILE
echo " There is ?$?"

test -s $FILE
echo " Non empty ?$?"

[ -r $FILE ]
echo " Can be read ?$?"

[ -w $FILE ]
echo " Can write ?$?"

[ -x $FILE ]
echo " Executable ?$?"

test -b $FILE
echo " Block device file ?$?"

test -c $FILE
echo " Character device file ?$?"

test -d $FILE
echo " Directory file ?$?"

test -f $FILE
echo " Ordinary documents ?$?"

test -L $FILE
echo " Soft link file ?$?"

test -S $FILE
echo " Socket file ?$?"

test -p $FILE
echo " Pipeline files ?$?"

Running results
 Insert picture description here

String test

s1 = s2 Test whether the contents of two strings are exactly the same
s1 != s2 Test whether the contents of two strings are different
-z s1 test s1 Is the length of the string 0
-n s1 test s1 Whether the length of the string is not 0

Digital test

a -eq b test a And b Whether it is equal or not
a -ne b test a And b Is it unequal
a -gt b test a Is it greater than b
a -ge b test a Greater than or equal to b
a -lt b test a Is less than b
a -le b test a Less than or equal to b
 Insert picture description here

Composite test

The first form : Command execution control
&&:
command1 && command2
&& Left command (command1) Successful implementation ( Return 0)shell To perform && The order on the right
(command2)
||
command1 || command2
|| The order on the left (command1) Not implemented successfully ( That is, return non 0)shell To perform || The order on the right
(command2)
The second form : Multiple conditional decision
 Insert picture description here

Control statement

if sentence

 Format 1 :
if [  Conditions 1 ]; then
 Execute the first procedure 
else
 Execute the second procedure 
fi
 Format two :
if [  Conditions 1 ]; then
 Execute the first procedure 
elif [  Conditions 2 ];then
 Execute the second procedure 
else
 Execute the procedure in the third paragraph 
fi

case sentence

case $ Variable name  in
“ The first variable content ”)
 Program segment 1 
;;
“ The second variable content ”)
 Segment II 
;;
*)
 Other program segments 
exit 1
esac

for sentence

 Form 1 :
for ((  Initial value ;  Limit value ;  Perform steps  ))
do
 Procedures section 
done
 Form 2 :
for var in con1 con2 con3 ...
do
 Procedures section 
done
 On the first cycle ,$var The content is con1
 On the second cycle ,$var The content is con2
 On the third cycle ,$var The content is con3
...
 When in After all the following values are assigned and the command is executed , The loop ends 

while sentence

while [ condition ]
do
 Procedures section 
done

When condition Enter when it is established while loop , until condition Exit the cycle only when it is not established

until sentence

until [ condition ]
do
 Procedures section 
done
 In this way while On the contrary , When condition Exit the loop when established , Otherwise continue the cycle .

break、continue

break
break The command allows you to jump out of the loop .
break Usually exit the loop or... After some processing case sentence
continue
continue The order is similar to break command
There is only one important difference , It won't jump out of the loop , Just skip this loop step

function

Some script segments repeat each other , If you can write a code block only once and reference it anywhere, it will improve the reusability of the code .
shell Allows a set of commands or statements to form a usable block , These blocks are called shell function .

Function definition and call

Define two forms of functions :

 Format 1 :
 Function name ()
{
    
 command  ...
}
 Format two :
function  Function name ()
{
    
 command  ...
}
 The format of the calling function is :
 Function name  param1 param2……

Function arguments

Using parameters is the same as using special variables in general scripts
$1,$2 …$9 equally

Function return value

Function can be used return End in advance and bring back the return value
return Returns... From a function , Use the last status command to determine the return value .
return 0 No error returned
return 1 Error returned

原网站

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