当前位置:网站首页>Is Shell Scripting really a big technology?

Is Shell Scripting really a big technology?

2022-06-12 14:00:00 Oriental invincible is me

In this paper, shell Script knowledge . It is best to have before study linux Command knowledge reserve .

After reading an article , The next time you look for a job, please write on your resume shell Script , bolt Q.

shell What is a script ?

shell A script is a script that contains shell Command script , Used to say linux command , You could say yes shell command .

function shell Script , It can realize such as installing software , Update software , execute , Restart the software, etc . such as , Install and deploy a package , It needs to be implemented shell Script . This shell Scripts are usually written by development engineers .

shell The script suffix is .sh, Such as a.sh, To execute shell Script , Just three steps

1、 create a file , Write the content of the document . Such as a.sh

2、 Make the script executable chmod +x a.sh 

3、 Execute the script   Execute... On the command line ./a.sh

Shell Variable

Variable naming

Such as your_name="runoob.com" 

  • 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 ( You can use help Command to view reserved keywords )

  Reference variables $yourname perhaps ${yourname} Curly braces are optional .

shell character string

Strings can be in single quotes , You can also use double quotes , You can also use no quotes .

str='this is a string'

Get string length :

string="abcd"
echo ${#string}

Add... Before the string variable #

Extract substring

From the string No  2  Characters begin to intercept  4  Characters :

string="runoob is a great site"
echo ${string:1:4} # Output unoo

Be careful : The index value of the first character is  0.

 shell Array

 Array name =( value 1  value 2 ...  value n)

The subscripts of array elements are 0 Numbered starting .

The general format for reading array element values is :

${ Array name [ Subscript ]}

Use  @  The symbol can get all the elements in the array , for example :

echo ${array_name[@]}

shell Of echo command

Used to output strings to the command line

echo " Hello "

  Note that the space is echo The space after must have  

Show escape characters

echo "\"It is a test\""

You need to use a backslash before the character

Show variable

echo $ Variable name

Such as echo $javahome

Show wrap

echo -e "OK \n" 

among -e To open the transfer

 

  No, -e Output effect

Output the results to a file

echo " Hello " > file name  

  File does not exist automatically created , If exist , The original content will be cleared and new content will be written .

Show command execution results

echo `date`

Show date Results of command

 

shell Pass parameters

adopt $n towards shell Script pass through parameters $0 Indicates the path of the execution file

Example : file a.sh The script is as follows :

echo "Shell Pass parameter instance !";
echo " File name of execution :$0";
echo " The first parameter is zero :$1";
echo " The second parameter is :$2";
echo " The third parameter is zero :$3";

perform :

When entering the execute file command , Write parameters , Pass it into the script and output .

$# The number of parameters passed to the script
$* Display all the parameters passed to the script in a single string .
Such as "$*" use 「"」 In a nutshell 、 With "$1 $2 … $n" Output all parameters in the form of .
$$ The current process the script runs ID Number
$! Of the last process running in the background ID Number
[email protected] And $* identical , But use quotation marks , And return each parameter in quotation marks .
Such as "[email protected]" use 「"」 In a nutshell 、 With "$1" "$2" … "$n" Output all parameters in the form of .
$- Show Shell Current options used , And set command Function the same .
$? Display the exit status of the last command .0 No mistakes , Any other value indicates an error .

  Example :

echo "Shell Pass parameter instance !";
echo " The number of parameters passed to the script :$#"
echo " File name of execution :$0";
echo " The first parameter is zero :$1";
echo " A single string shows all the parameters passed to the script :$*";
echo " The process in which the script runs ID:$$";
echo " Of the last process running in the background ID:$!"
echo " Output all parameters passed to the script :#@";
echo " Show shell Current options used :$-";
echo " Displays the last exit status of the command :$?";
 

perform :

 

$* And [email protected] difference :

  • The same thing : All references to all parameters .
  • Difference : Only in double quotes . Suppose you write three parameters when the script runs 1、2、3,, be " * " Equivalent to "1 2 3"( Passed a parameter ), and "@" Equivalent to "1" "2" "3"( Three parameters are passed ).

echo "-- \$* demonstration ---"
for i in "$*"; do
    echo $i
done

echo "-- \[email protected] demonstration ---"
for i in "[email protected]"; do
    echo $i
done 

 

 Shell Array

Only one-dimensional arrays are supported , Multidimensional arrays are not supported .

From the subscript 0 Start , Elements are separated by spaces

Define an array

Mode one : Array name =(value0 value1 value2...)

Mode two : Array name [0]=value0

Little surprise :vi In command mode :%d The contents of the file can be emptied

Read array

The general format for reading array element values is :

${array_name[index]}
my_array=(A B "C" D)

echo " The first element is : ${my_array[0]}"
echo " The second element is : ${my_array[1]}"
echo " The third element is : ${my_array[2]}"
echo " The fourth element is : ${my_array[3]}"

Get all the elements in the array

Use @ or * You can get all the elements in the array

my_array[0]=A
my_array[1]=B
my_array[2]=C
my_array[3]=D

echo " The elements of the array are : ${my_array[*]}"
echo " The elements of the array are : ${my_array[@]}"

Gets the length of the array :

echo " The number of array elements is : ${#my_array[*]}"
echo " The number of array elements is : ${#my_array[@]}"

Shell printf command

default printf Don't like  echo  Automatically add line breaks , We can add... Manually  \n.

printf  format-string  [arguments...]

Parameter description :

  • format-string:  Control string for format
  • arguments:  For parameter list .

echo "Hello, Shell"
printf "Hello, Shell\n"

in addition printf You can format strings

%s %c %d %f  It's all format substitutions ,%s  Output a string ,%d  Integer output ,%c  Output a character ,%f  Output real number , Output in decimal form .

Shell Basic operators

Arithmetic operator

Other commands such as awk expr

#!/bin/bash

val=`expr 2 + 2`
echo " The sum of the two is : $val"

  Note that this is a back quote, not a single quote There must be a space between numbers and operators

a=10
b=20

val=`expr $a + $b`
echo "a + b : $val"

val=`expr $a - $b`
echo "a - b : $val"

val=`expr $a \* $b`
echo "a * b : $val"

val=`expr $b / $a`
echo "b / a : $val"

val=`expr $b % $a`
echo "b % a : $val"

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

  Relational operator

 a=10
b=20

if [ $a -eq $b ]
then
   echo "$a -eq $b : a be equal to b"
else
   echo "$a -eq $b: a It's not equal to b"
fi
if [ $a -ne $b ]
then
   echo "$a -ne $b: a It's not equal to b"
else
   echo "$a -ne $b : a be equal to b"
fi
if [ $a -gt $b ]
then
   echo "$a -gt $b: a Greater than b"
else
   echo "$a -gt $b: a No more than b"
fi
if [ $a -lt $b ]
then
   echo "$a -lt $b: a Less than b"
else
   echo "$a -lt $b: a Not less than b"
fi
if [ $a -ge $b ]
then
   echo "$a -ge $b: a Greater than or equal to b"
else
   echo "$a -ge $b: a Less than b"
fi
if [ $a -le $b ]
then
   echo "$a -le $b: a Less than or equal to b"
else
   echo "$a -le $b: a Greater than b"
fi

remarks :shell Scripts are space sensitive , Such as if There must be a space after  

Boolean operator

  Logical operators

String operators  

  File test operators

 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 " 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

 

Shell Process control

if sentence

if condition
then
    command1 
    command2
    ...
    commandN 
fi

if-else

if condition
then
    command1 
    command2
    ...
    commandN
else
    command
fi

if else -if else

if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi

Determine whether two variables are equal  

a=10
b=20
if [ $a == $b ]
then
   echo "a be equal to b"
elif [ $a -gt $b ]
then
   echo "a Greater than b"
elif [ $a -lt $b ]
then
   echo "a Less than b"
else
   echo " There are no conditions that meet "
fi

 

 for loop

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done

in The list can contain substitutions 、 String and file name . 

for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

 

 while sentence

while condition
do
    command
done

int=1
while(( $int<=5 ))
do
    echo $int
    let "int++"
done 

while Loops can be used to read keyboard information .

Infinite loop

Infinite loop syntax format :

while :
do
    command
done

 until loop

until Loop through a series of commands until the condition is true Stop when .

until condition
do
    command
done

Use until Command to output 0 ~ 9 The number of :

#!/bin/bash

a=0

until [ ! $a -lt 10 ]
do
   echo $a
   a=`expr $a + 1`
done

 case ... esac

amount to switch case sentence , Multi branch selection structure

Every case The branch begins with a right parenthesis , Use two semicolons  ;;  Express break, The end of execution , Jump out of the whole case ... esac sentence ,esac( Namely case In turn, ) As the closing tag .

It can be used case Statement matches a value with a pattern , If the match is successful , Execute the matching command .

Value must be followed by word  in, The first mock exam must be closed with right brackets. . Value can be variable or constant , Match found that after the first mock exam meets a certain pattern, , During this period, all commands are executed until  ;;.

Value will detect every matching pattern . Once the patterns match , After the corresponding command of matching mode is executed, other modes will not be continued . If there is no matching pattern , Use the asterisk * Capture the value , Then execute the following command .

case  value  in
 Pattern 1)
    command1
    command2
    ...
    commandN
    ;;
 Pattern 2)
    command1
    command2
    ...
    commandN
    ;;
esac

The following script prompts for 1 To 4, Match with each pattern :

echo ' Input 1 To 4 Number between :'
echo ' The number you enter is :'
read aNum
case $aNum in
    1)  echo ' You chose 1'
    ;;
    2)  echo ' You chose 2'
    ;;
    3)  echo ' You chose 3'
    ;;
    4)  echo ' You chose 4'
    ;;
    *)  echo ' You didn't enter 1 To 4 Number between '
    ;;
esac

Out of the loop

break command

break The command allows you to jump out of all loops ( Terminate all loops after execution ).

The following script is a loop , When the input is not 1 To 5 Between the numbers when jumping out of the loop .

#!/bin/bash
while :
do
    echo -n " Input 1 To 5 Number between :"
    read aNum
    case $aNum in
        1|2|3|4|5) echo " The number you enter is  $aNum!"
        ;;
        *) echo " The number you entered is not 1 To 5 Between ! Game over "
            break
        ;;
    esac
done

continue

continue Command and break Command similar , There's only one difference , It doesn't jump out of all loops , Just jump out of the current loop .

#!/bin/bash
while :
do
    echo -n " Input 1 To 5 Number between : "
    read aNum
    case $aNum in
        1|2|3|4|5) echo " The number you enter is  $aNum!"
        ;;
        *) echo " The number you entered is not 1 To 5 Between !"
            continue
            echo " Game over "
        ;;
    esac
done 

Run code discovery , When the input is greater than 5 Digital time , The loop in this case does not end , sentence  echo " Game over "  It will never be carried out . 

Shell test command

Shell Medium test The command is used to check if a condition holds , It can do numerical 、 Character and file testing .

The numerical test  

num1=100
num2=100
if test $[num1] -eq $[num2]
then
    echo ' Two numbers are equal !'
else
    echo ' The two numbers are not equal !'
fi

In code  []  Perform basic arithmetic operations

String test

num1="goodmorning"
num2="goodevening"
if test $num1 = $num2
then 
  echo " Two strings are equal "
else
  echo " Two strings are not equal "
fi 

if test $num1 != $num2
then
   echo " Two strings are not equal "
else
  echo " Two strings are equal "
fi

if test -z $num1
then 
  echo " The string length is zero "
else
  echo " String length is not zero "
fi

if test -n $num1
then 
  echo " String length is not zero "
else
  echo " The string length is zero "
fi
 

File test

if test -e a.sh
then echo " File exists "
else echo " file does not exist "
fi


if test -r a.sh
then echo " Documents are readable "
fi

if test -w a.sh
then echo " Documents can be written "
fi

if test -x a.sh
then echo " The document is executable "
fi

if test -s a.sh
then echo " The file exists and has at least one character "
fi


if test -d a.sh
then echo " The directory file exists "
fi

if test -f a.sh
then echo " The file exists and is a normal file "
fi

if test -c a.sh
then echo " The file exists and is a special character file "
fi

if test -b a.sh
then echo " File exists and is a block special file "
fi

 

 shell function

stay shell Function can be defined in , And call .

demoFun(){
    echo " This is my first  shell  function !"
}
echo "----- The function starts executing -----"
demoFun
echo "----- The function is finished -----"

 

  with return Function of

funWithReturn(){
    echo " This function will add two input numbers ..."
    echo " Enter the first number : "
    read aNum
    echo " Enter the second number : "
    read anotherNum
    echo " The two figures are  $aNum  and  $anotherNum !"
    return $(($aNum+$anotherNum))
}
funWithReturn
echo " The sum of the two numbers entered is  $? !"

$? You can get the return value of the function

Function parameter

stay Shell in , You can pass parameters to a function when you call it . Inside the body of the function , adopt $n To get the value of the parameter , for example ,$1 Represents the first parameter ,$2 Represents the second parameter ...

funWithParam(){
    echo " The first parameter is zero  $1 !"
    echo " The second parameter is  $2 !"
    echo " The tenth parameter is  $10 !"
    echo " The tenth parameter is  ${10} !"
    echo " The eleventh parameter is  ${11} !"
    echo " The total number of parameters is  $#  individual !"
    echo " Output all parameters as a string  $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73

 

$10 Can't get the tenth parameter , Getting the tenth parameter requires ${10}. When n>=10 when , Need to use ${n} To get the parameters . 

Special characters are used to handle parameters :

原网站

版权声明
本文为[Oriental invincible is me]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121353370636.html