Theory+Practice: shell case statement for/while/until loop statement, function, array-full dry goods

Preface:

Single quotation marks denote pure symbols with double quotation table strings

  • case multi-branch statement
  • Loop statement
    • for loop statement
    • while loop statement
    • until loop statement
  • shell Function
  • shell array

One: the structure of case statement

1.1 case structure

  • Multi-branch representation: if statement, case statement

  • A case statement can use regular expressions, which are described later

  • Execute different command programs for different values of variables

In case (?) denotes the end of a sentence

If a fixed value is matched, most use caes, which is appropriate for a fixed value

If a range of intervals is matched, most use if else statements, which apply to a range

*No need to add after

1.2 case Execution Process Flow Chart

  • case executes different command sequences for different values of a variable

  • The case variable matches the pattern, and the if variable matches the condition

Example application of 1.3 case statement

1.3.1 Example 1: Key type recognition

  • Prompt user for a character
  • Determine if the character is a letter, number, or other character
#/bin/bash
 Read-p "Press a key, I can test if the year's key is alphanumeric or other characters"
case "$jian" in
[0-9])
     echo "You are pressing a number"
     ;;
[a-z]|[A-Z])
     echo "You pressed the letter"
     ;;
*)
     echo "You pressed a special character"
esac
[root@localhost opt]# sh shibiejijian.sh
 Please press a key. I can test if the year's key is alphanumeric or other character 8
 You are pressing a number
[root@localhost opt]# sh shibiejijian.sh
 Please press a key. I can test if the year's key is alphanumeric or any other character a
 You pressed the letter
[root@localhost opt]# sh shibiejijian.sh
 Please press a key. I can test if the year's key is alphanumeric or other character A
 You pressed the letter
[root@localhost opt]# sh shibiejijian.sh
 Please press a key. I can test if the year's key is alphanumeric or any other character @
You are pressing special characters

1.3.2 Please enter your results to judge whether you are qualified or not

#!/bin/bash
 Read-p "Please enter your results" cj
case "$cj" in
[0-9]|[1-5][0-9])
    echo "Unqualified results"
    ;;
7[0-4]|6[0-9])
    echo "Achieved"
    ;;
7[5-9]|8[0-4])
    echo "Good results"
    ;;
8[5-9]|9[0-9]|100)
    echo "Excellent results"
    ;;
*)
    echo "You entered incorrect results"
esac

[root@localhost opt]# sh chengjicase.sh 
Please enter your score-1
 You entered incorrect results
[root@localhost opt]# sh chengjicase.sh 
Please enter your score 0
 Unqualified results
[root@localhost opt]# sh chengjicase.sh 
Please enter your score 9
 Unqualified results
[root@localhost opt]# sh chengjicase.sh 
Please enter your score 10
 Unqualified results
[root@localhost opt]# sh chengjicase.sh 
Please enter your score 59
 Unqualified results
[root@localhost opt]# sh chengjicase.sh 
Please enter your score 60
 Achievement Qualification
[root@localhost opt]# sh chengjicase.sh 
Please enter your score 74
 Achievement Qualification
[root@localhost opt]# sh chengjicase.sh 
Please enter your score 75
 Good results
[root@localhost opt]# sh chengjicase.sh 
Please enter your score 7^H84
 You entered incorrect results
[root@localhost opt]# sh chengjicase.sh 
Please enter your score 84
 Good results
[root@localhost opt]# sh chengjicase.sh 
Please enter your score 85
 Excellent results
[root@localhost opt]# sh chengjicase.sh 
Please enter your score 99
 Excellent results
[root@localhost opt]# sh chengjicase.sh 
Please enter your score 100
 Excellent results
[root@localhost opt]# sh chengjicase.sh 
Please enter your score 101
 You entered incorrect results
[root@localhost opt]# 

1.3.3 Example 2: Scripting system services

  • Use parameters such as start, stop, restart to control services
  • Service control instructions are passed in through the location variable $1

The loop structure of the for statement

2.1 for statement overview

  • Read different variable values to execute the same set of commands one by one

Interruption of control cycle

A list of values is a collection;

Reading assignments from top to bottom to execute commands is called traversal.

for can be thought of as a pickup gun that clears shopping carts in a supermarket

2.2 for Statement Flowchart

2.3 for Statement Application Example

2.3.1 Example 1 - Add users in bulk

  • User names are stored in the users.txt file, one per line
  • Initial password set to 123 456
  • Validation script
#!/bin/bash
for ((i=1;i<=4;i++))
  do
     useradd "admin$i" &> /dev/null
     echo "123456" | passwd --stdin "admin$i" &> /dev/null
     echo "User admin$i created successfully"
  done
~     
[root@localhost opt]# sh users.sh
 User admin1 created successfully
 User admin2 created successfully
 User admin3 created successfully
 User admin4 created successfully

2.3.2 Example 2 - Use to check host status based on IP address

  • IP addresses are stored in the ipadds.txt file, one per line
  • Use the ping command to detect the connectivity of hosts

[root@localhost opt]# vim addr.sh 
#!/bin/bash
List=$(cat /opt/ipadds.txt)
for ((i=0;i<=256;i++))
do
   ping -c 3 -i 0.2 -W 1 192.168.10.$i &> /dev/null
     if [ $? =  0 ]
       then
        echo "192.168.10.$i is up"
     else
        echo "192.168.10.$i is down"
     fi
done

2.3.3 Arrange 1-10 from top to bottom

#!/bin/bash
for ((i=1;i<=10;i++))
  do
echo "$i"
  done

The double semicolon for cannot be removed

Even Sum of 2.3.4:1-100

sum=0
for ((i=0;i<=100;i+2))
do
     let sum+=$i
done
    echo "$sum"

i+=2 means i=i+2

continue skips its part of the statement and recycles it

let command, meaning reassignment, is equivalent to adding a number to the sum

When break sees break, it exits the loop directly

$RANDOM is a random value

Use it to take the rest to fix the range of random numbers

2.3.5 Guess Price

  • Method One
#!/bin/bash
echo  "Say nothing and come and guess the price"
b=`expr $RANDOM % 1000`
n=0
read -p "Enter the number in your mind and guess the price of today's offer (0)-999)?" a
while [ $a -ne $b ]
do
   if [ $a -gt $b ]
     then
       echo "You think too much of it"
read -p "Enter the number in your mind and guess the price of today's offer (0)-999)?" a
    let n++
     else
       echo "You underestimate its price"
     let n++
read -p "Enter the number in your mind and guess the price of today's offer (0)-999)?" a
   fi
done
   let n++
    echo "Congratulations, you guessed right. His price is $b,You guessed it all $n Unfortunately you have no money to buy it"
    exit 0
  • Method 2
#!/bin/bash
n=0
echo "This is a game of guessing the price at 1~1000 Scope."
jiage=$(expr $RANDOM % 1000)
while true
do
read -p "Please enter your guessed price:" cai
if [ $cai -eq $jiage ]
  then
         let n++
         echo "Congratulations on your guess!Its price is: $jiage.You guessed it all $n second."
         exit 0
elif [ $cai -gt $jiage ]
 then
        let n++
        echo "You guess the price is high,Guess a little lower."
elif [ $cai -lt $jiage ]
 then
        let n++
        echo "You guess the price is low,Guess a little higher."
fi
done

2.3.6999 Multiplication Table

  • Method One
#!/bin/baash
for ((i=1;i<=9;i++))
do
  for ((a=1;a<=i;a++))
  do
      echo -n "$i x $a=$(expr $i \* $a)  " 
   if  [ $a -eq $i ]
   then
      echo -e '\n' 
   fi
  done
done
  • Method 2

echo's help help help

NAME (Name)
       echo - Displays a line of text

SYNOPSIS (Overview)
       echo[OPTION]... [STRING]...

DESCRIPTION (Description)
       Allow STRING(s) on standard output.

       -n does not output line breaks at the end of the line.

       -e allows the characters listed below to be interpreted with the backslash escape.

       -E prohibits interpretation of those sequences in STRINGs.

       --help Displays help and exits (must be run separately)

       --version outputs version information and exits (must run separately)

       In the absence of -E, the following sequences can be recognized and replaced internally:

        The ASCII code for the \NNN character is NNN (octal)

        \Backslash

        \a Alarm (BEL)

        \b Backspace Character

        \c Prohibits trailing line breaks

        \f Page Break

        \n Line Break

        \r carriage return

        \t Horizontal Tab

        \v Vertical Tab
  • Nine-nine multiplication table for diamonds
#!/bin/bash
for ((i=1;i<=17;i++))
do
  if [ $i -le 9 ];then
  k=$(expr 45 - $(expr $i \* 5))
     until [ $k -eq 0 ]
     do
     echo -n "     "
     let k-=5
     done
       for ((j=1;j<=i;j++))
       do
       echo -n "$i*$j=$(expr $i \* $j)    "
         if [ $i -eq $j ]
         then
         echo -e '\n'
         fi
       done
  else
  xi=$(expr 18 - $i)
  xk=$(expr 45 - $(expr $xi \* 5))
      until [ $xk -eq 0 ] 
      do
      echo -n "     "
      let xk-=5
      done
       for ((xj=1;xj<=xi;xj++))
       do
       echo -n "$xi*$xj=$(expr $xi \* $xj)    "
         if [ $xj -eq $xi ]
         then
         echo -e '\n' 
         fi
       done
  fi
done

The structure of the while statement

3.1 Overview of while statements

  • Repeatedly test a condition and execute it as long as the condition is valid

3.2 Example while statement application

3.2.1 Browsing Commercial Street

  • Method One
#!/bin/bash:
echo "Welcome to the Commercial Street, take a stroll"
qian=0
a=1.Computer City
b=2.Couture
c=3.Steamed bread shop
d=4.Swimming Shop
goumai=You bought it
while true
do
echo "1.Computer City"
echo "2.Couture"
echo "3.Steamed bread shop"
echo "4.Swimming Shop"
read -p "There are computer stores, clothing stores, bun shops and swimming suit stores on the commercial street. Which one do you want to go to?(Enter serial number)" nub
case $nub in
1)
echo "===========Welcome to Computer City=========================="
echo "1.Mobile phone 800 yuan"
echo "2.Computer 1200 yuan"
echo "3.Charger Line 15 Yuan"
echo "4.Keyboard $100"
read -p "There are above items for you to choose from---Do you have anything you want to buy?( yes/no)" yesno
while true
do
  if [ $yesno = yes ]
  then
    read -p "Enter the serial number of the item you want to buy" xuhao
      case $xuhao in
      1)
        echo "You bought a mobile phone worth 800 yuan"
        let qian=800+$qian
           goumai=$goumai Mobile,
        ;;
      2)
        echo "You bought a computer worth 1,200 yuan"
        qian=`expr $qian + 1200`
           goumai=$goumai Mobile,
        ;;
      3)
        echo "You bought a charging cord worth 15 yuan"
        qian=`expr $qian + 15`
           goumai=$goumai Mobile,
        ;;
      4)
        echo "You bought a keyboard worth $100"
        qian=`expr $qian + 100`
           goumai=$goumai Mobile,
        ;;
      *)
        echo "There's nothing you want in the store"
        break
      esac
  else
    echo "If you don't want to buy it, let's go"
    break
  fi
done
  ;;
2)
echo "===========Welcome to Clothing Store=========================="
echo "1.Shoes 120 yuan"
echo "2.85 yuan for trousers"
echo "3.Hat 15 yuan"
echo "4.Belt 320 yuan"
read -p "There are above items for you to choose from---Do you have anything you want to buy?( yes/no)" yesno
while true
do
  if [ $yesno = yes ]
  then
    read -p "Enter the serial number of the item you want to buy" xuhao
      case $xuhao in
      1)
        echo "You bought shoes worth 120 yuan"
        let qian=120+$qian
           goumai=$goumai Shoes,
        ;;
      2)
        echo "You bought pants worth 85 yuan"
        qian=`expr $qian + 85`
           goumai=$goumai Pants,
        ;;
      3)
        echo "You bought a hat worth 15 yuan"
        qian=`expr $qian + 15`
           goumai=$goumai Hat,
        ;;
      4)
        echo "You bought a belt worth 320 yuan"
        qian=`expr $qian + 320`
           goumai=$goumai Belt,
        ;;
      *)
        echo "There's nothing you want in the store"
        break
      esac
  else
    echo "If you don't want to buy it, let's go"
    break
  fi
done
  ;;
3)
echo "===========Welcome to the bun shop=========================="
echo "1.Shandong Grocery Pancake 15 Yuan"
echo "2.Qingdao lobster stuffed bun 15 yuan"
echo "3.Simple white steamed bread 1 yuan"
echo "4.1000 yuan for non-simple white steamed bread"
read -p "There are above items for you to choose from---Do you have anything you want to buy?( yes/no)" yesno
while true
do
  if [ $yesno = yes ]
  then
    read -p "Enter the serial number of the item you want to buy" xuhao
      case $xuhao in
      1)
        echo "You bought Shandong Sundry Pancake worth 15 Yuan"
        let qian=15+$qian
           goumai=$goumai Shandong Granula Pancakes,
        ;;
      2)
        echo "You bought Qingdao lobster stuffed buns worth 15 yuan"
        qian=`expr $qian + 15`
           goumai=$goumai Qingdao lobster buns,
        ;;
      3)
        echo "You bought a simple white bun"
        qian=`expr $qian + 1`
           goumai=$goumai White steamed bread,
        ;;
      4)
        echo "You bought a lot of white steamed bread and got the lady's heart"
        qian=`expr $qian + 1000`
           goumai=$goumai Boss's heart,
        ;;
      *)
        echo "There's nothing you want in the store"
        break
      esac
  else
    echo "If you don't want to buy it, let's go"
    break
  fi
done
  ;;
4)
echo "===========Welcome to the swimwear shop=========================="
  echo "1.Swimming cap $10"
  echo "2.Swimwear 15 yuan"
  echo "3.Swimming mirror $12"
  echo "4.Bikini 32 yuan"
read -p "There are above items for you to choose from---Do you have anything you want to buy?( yes/no)" yesno
while true
do
  if [ $yesno = yes ]
  then
    read -p "Enter the serial number of the item you want to buy" xuhao
      case $xuhao in
      1)
        echo "You bought a swimming cap worth 10 yuan"
        let qian=10+$qian
           goumai=$goumai Swimming cap,
        ;;
      2)
        echo "You bought a swimsuit worth 15 yuan"
        qian=`expr $qian + 15`
           goumai=$goumai Swimwear,
        ;;
      3)
        echo "You bought a swimming glass worth 12 yuan"
        qian=`expr $qian + 12`
           goumai=$goumai Swimming goggles,
        ;;
      4)
        echo "You bought a bikini worth 32 yuan"
        qian=`expr $qian + 32`
           goumai=$goumai Bikini,
        ;;
      *)
        echo "There's nothing you want in the store"
        break
      esac
  else
    echo "If you don't want to buy it, let's go"
    break
  fi
done
  ;;
*)
  echo "Input error, do not take you shopping"
  echo "You spent the time shopping $qian Yuan, $goumai"
  exit 1
esac
done
  • Method 2
#!/bin/bash
  2 qian=0
  3 n=0
  4 echo "======Welcome to the mall where you must pay for it==============="
  5 
  6 for ((i=1;i<=4;i++));do
  7 echo "===========Come to $i Home Shop============="
  8 read -p "Come play, little handsome?--Whether to shop ( yes/no)" yesno
  9   case $yesno in
 10   yes)
 11   echo "You won't regret it. Look at the merchandise"
 12   echo "1.300 yuan for stockings worn by hostess"
 13   echo "2.900 yuan for a bottle you buy and regret"
 14   echo "3.Moving rechargeable twisted egg 150 yuan"
 15   read -p "Which do you want to buy, one by one in sequence"   xuhao
 16     case $xuhao in
 17     1)
 18     echo "You chose the socks for the hostess and spent 300 yuan"
 19     let qian+=300
 20     let n++
 21     ;;
 22     2)
 23     echo "You chose a bottle that you regretted buying. It was empty and you spent 900 yuan for nothing."
 24     let qian+=900
 25     let n++
 26     ;;
 27     3)
 28     echo "You chose the movable rechargeable Twist Egg. It would be a surprise for the hostess."
 29     let qian+=150
 30     let n++
 31     ;;
 32     *)
 33     echo "Boy, there's not everything in the store yet. Check again"
 34     esac
 35     while true
 36     do
 37     read -p "Do you want to keep looking ( yes/no)" yesn
 38       if [ $yesn = yes ];then
 39       echo "Snore, young man is very rich"
 40       echo "You won't regret it. Look at the merchandise"
 41       echo "1.300 yuan for stockings worn by hostess"
 42       echo "2.900 yuan for a bottle you buy and regret"
 43       echo "3.Moving rechargeable twisted egg 150 yuan"
 44       read -p "What to buy this time (please enter the serial number)" xuh
 45         case $xuh in
 46         1)
 47         echo "You chose the socks for the hostess and spent 300 yuan"
 48         let qian+=300
 49         let n++
 50         ;;
 51         2)
 52         echo "You chose a bottle that you regretted buying. It was empty and you spent 900 yuan for nothing."
 53         let qian+=900
 54         let n++
 55         ;;
 56         3)
 57         echo "You chose the movable rechargeable Twist Egg. It would be a surprise for the hostess."
 58         let qian+=150
 59         let n++
 60         ;;
 61         *)
 62         echo "Boy, there's not everything in the store yet. Check again"
 63         esac
 64       else
 65       break
 66       fi
 67       done
 68   ;;
 69   no)
 70   echo "Unfortunately, please come again"
 71   ;;
 72   *)
 73   echo "Boy, you're skinny. I won't let you in until you don't come in." 
 74   esac
 75 done
 76   echo "=======Shopping over to see how much money you've been slaughtered======="
 77   echo "You spent $qian Yuan, bought it $n Items"

While true represents an infinite loop in which an if statement containing a break is added to exit the loop

3.2.2 Guess who's luckiest

  • Method One
#!/bin.bash
n=0
c=0
b=0
for ((i=1;i<=10;i++))
do
shuzi=`expr $(expr $RANDOM % 2) + 1`
xingming=`cat /opt/jbxx/mingdan.txt | grep $shuzi | awk -F: '{print $2}'`
# cat personnel list
     case "$shuzi" in
    1)
      let  n++
      ;;
     2)
      let  c++
      ;;
      *)
      let  b++
     esac
   echo "$xingming"
done
echo "zhangsan $n Secondary, lisi $c Secondary, wangwu $b second" 
  • Method 2

  • Method Three

3.2.3 Bulk Add Users

  • User names start with stu and are numbered numerically
  • A total of 20 users have been added, stu1, stu2, stu3...
  • Initial password set to 123 456
#!/bin/bash
i=1
until [ $i -gt 20 ];do
useradd stu$i
#echo "123456" | passwd --stdin stu$i &> /dev/null
  let i++
echo "user stu$i Created successfully"
done
===========================================================
#!/bin/bash
i=1
while [ $i -le 20 ];do
userdel -r  stu$i
#echo "123456" | passwd --stdin stu$i 
  let i++
echo "user stu$i Delete succeeded"
done

3.2.4 Guess Commodity Price Game

  • Obtaining random numbers from the variable RANDOM
  • Prompt user to guess and record number of times, quit the loop after guessing
#!/bin/bash
n=1
jiage=$[RANDOM%1000+1]
read -p "Please enter the price in your mind:" cai
while [ $cai != $jiage ];do
   if [ $cai -gt $jiage ];then
   echo "The price you entered is high"
   let n++
read -p "Please enter the price in your mind:" cai
    else
    echo "The price is low"
   let n++
read -p "Please enter the price in your mind:" cai
   fi
done
echo "Congratulations, you guessed. The price of this item is $jiage,You guessed it all $n second"
exit 0

Four: until statement

Structure of 4.1 until statement

4.2 until statement application example

4.2.1 Calculate the sum of 1-50

  • Calculate the sum of 1-50 by cyclic accumulation
#!/bin/bash
num=0
n=1
until [ $n -gt 50 ];do
  let  sum+=$n
  let n++
done
echo "$sum"

4.2.2 Send online messages to specified users

  • If the user is not online (not logged on to the system), try every 10 minutes until the user logs on to the system and sends the message again.

  • User names and messages are passed to scripts through location parameters

  • Method One

    #!/bin/bash
    #Determine whether to enter parameters
    if [ $# = 0 ];then
    echo "enter one user name"
    exit 1
    fi
    #Determine whether the user exists
    if grep "^$1" /etc/passwd &> /dev/null;then :
    else
     echo "user does not exist"
    
     exit 2
    fi
    #Determine whether users are online
    until who | grep "$1" &> /dev/null;do
      echo "User not online"
      sleep 3
    done
    #Send message to user
    
    echo "$*" | write "$1"
    
  • Method 2

Can't be empty in the N and else

5: shell function

  • Write command sequences together in format
  • Easy reuse of command sequences
  • shell function definition
  • Methods of calling functions
    • Function name [parameter 1] [parameter 2]
    • Parameter 1 is the positional parameter $1, and parameter 2 is the positional parameter $2

5.1 Function Format

Encapsulate function return value

There are two types of return values, return status - - call using $?

echo value - call uses assignment variable

The state is adjusted by $? And the value by variable

Pass-in parameters are passed in with location variables

5.2 Example

5.2.1 Sum of two numbers

  • Define a function by sum(){}
  • Use the read command to interactively enter two numbers and sum them
#!/bin/bash
function qiuehe(){
  sum=`expr $1 + 10`
    #echo "$sum"
    return $sum
    echo "$?"
}
qiuehe $1
~            

5.2.2 Write user-defined functions that can be used after logging in to the system and execute the command servicectl httpd start

  • Edit user-defined function file/root/function
  • Load executable function file/root/function in the current shell
  • Add source/root/function command to ~/.bash file

  • systemctl start httpd
  • service httpd start

    Create a new service httpd start command

Ideas:

1. Verify grammar format

2. Verify version type, linux version, only centos7 can use servicectl command 

View version type cat/etc/centos-release

3. Execute the command servicectl httpd start
  • Method One
#!/bin/bash
function servicectl (){
#Determine if the format is correct
if [ $# -lt 2 ];then
        echo "Error in usage, format: servicectl <service name> <option>"
        exit 1
fi
#Determine if the system version is centos7
if [ $(cat /etc/centos-release |awk '{print $4}' | awk -F. '{print $1}') -ge 7 ];then
        echo "Compliant Version centos7 And above requirements, can be used servicectl command"
        service $1 $2
else
   echo "Your version is too low to use!"
fi
}
  • Method 2
#!/bin/bash
#This is a custom function that users can use after the system is started
#Function: Start the service on
#Determine if the script is properly formatted, that is, the number of parameters
function format(){
echo $#
if [ $# -ne 2 ]
then
 echo "The parameter you entered is not in the correct format,UsageMethod:serve <cmd> <serve> "
 exit 1
fi
}
#Determine if the Linux version used is Centos7
function version(){
echo "hello"
num=$(cat /etc/centos-release |awk '{print $4}' |awk -F. '{print $1}')
if [ $num -eq 7 ]
then
 echo "Your system version is centos Version 7 of and ready to execute service startup script, please wait"
fi 
}
#Service Start
function serve(){
 format $1 $2
 version
 case $2 in 
 start)

  systemctl start httpd
  ;;
 stop)
  systemctl stop httpd
  ;;
 *)
  echo "nothing need to do"
 esac
}

Six: shell array

6.1 Application Scenarios

Groups are good for storing the same type of data, and this also applies to java

Data can be stored in an array of data types

1.Integer init 1 2 3 100

2. long Integer long

3. Floating point single precision float 4 bytes, floating point with decimal point

4.string string: char character takes up one byte in English alphabet character a; Chinese character takes up two bytes in male, while in java all characters take up two bytes

5.boolean Boolean Boolean value ture and false

6.date date date

7.html Markup Language exists as a tag

Subscripts or indexes are used to find data in an array

  • Get Array Length

Index starts at 0,

Array has length, the following example is 4 - Array length

  • Get element length

The most taboo about crossing an array is that it depends on the length of your array - abc[4], so it's crossing the boundary

Index subscript must start with 0

  • Traversing Elements

Traversal Elements: Loop

  • Element Slices
  • Element substitution
  • Element Delete
  • ·······

6.2 Array Definition Method

  • Data is separated from data by spaces, that is, array elements are separated by spaces

6.2.1 Method 1

Array name= (value0 value1 value2...)

abc = (10 20 30 )

The simplest way, dynamic input, is also known as variable-length arrays

6.2.2 Method 2

Array name=([0] = value [1] = value [2] = value...)

abc = ([0] = 10 [1] = 20 [2] = 30 .......)

6.2.3 Method 3

List name="value0 value1 Value2..."

Array name=($list name)

Give the array name a list name with data in it

6.2.4 Method 4

Array name [0]="value" abc[0] = 10

Array name [1]="value" abc[1] = 20

Array name [2]="value" abc[2] = 30

......

This method is not recommended

6.3 Data types included in the array

  • value type
  • Character type
    • Use or Define

Cannot place object

There is no two-dimensional array in the shell

6.4 shell Array Operations

  • Get the length of the array - -${array name [@/*]}
    • @or, which can be interpreted as a wildcard symbol, similar to $, to view all the data in the array ${abc[*]}, ${abc[@]}
  • Read a subscript assignment - ${array name [subscript]}
    • ${abc[2]}
  • Array traversal
  • ${#abc[]}, that is, on the basis of obtaining the length of the array, add # to the array name and echo looks at ${#abc[]} the number of data in the array, similar to $#
  • That is, ${abc[*]} plus a #sign is a statistic; without a #sign, all the positions in the array are displayed.

Array traversal example

6.4.1 ratio size

max=0
for ((i=1;i<=5;i++))
do
read -p "Please enter # $i Numbers" num
a=i-1
abc[a]=$num
if [ ${abc[a]} -gt $max ]
then
max=${abc[a]}
fi
done
echo ${abc[*]} 
echo "Maximum value is $max"

6.4.2 Sort arrays, insert numbers, and reorder them

#/bin/bash
  2 for ((i=1;i<=5;i++))
  3 do
  4 read -p "Please enter # $i Numbers" num
  5 a=$i-1
  6 c=$a-1
  7 abc[a]=$num
  8 done
  9 #Descending order
 10 b=0
 11 for ((j=0;j<=c;j++))
 12 do
 13   for ((i=0;i<=c;i++))
 14   do
 15     ii=`expr $i + 1`
 16     if [ ${abc[$i]} -le ${abc[$ii]} ]
 17     then
 18     b=${abc[$i]}
 19     abc[$i]=${abc[$ii]}
 20     abc[$ii]=$b
 21     fi
 22   done
 23 done
 24 echo ${abc[*]}
 #Ascending order
 25 mb=0
 26 for ((j=0;j<=c;j++))
 27 do
 28   for ((i=0;i<=c;i++))
 29   do
 30     ii=`expr $i + 1`
 31     if [ ${abc[$i]} -ge ${abc[$ii]} ]
 32     then
 33     mb=${abc[$i]}
 34     abc[$i]=${abc[$ii]}
 35     abc[$ii]=$mb
 36     fi
 37   done
 38 done
 39 echo ${abc[*]}
 40 read -p "Enter the number you want to interpolate" xnum
 41 i=$a+1
 42 abc[i]=$xnum
 43 
 44 for ((f=0;f<=i;f++))
 45 do
 46   for ((g=0;g<=a;g++))
 47   do
 48     gg=$(expr $g + 1)
 49     if [ ${abc[$g]} -le ${abc[$gg]} ]
 50     then
 51     b=${abc[$g]}
 52     abc[$g]=${abc[$gg]}
 53     abc[$gg]=$b
 54     fi
 55   done
 56 done
 57 echo ${abc[*]}

Expand

1. Find the solution of ax^2+bx+c=0, with a, b, C as manual inputs

  • Square root example
#!/bin/bash
a=9
b=$(awk -v x=$a 'BEGIN{print sqrt(x)}')
echo $b
b=$(echo "$a" | awk '{print sqrt($1)}')
echo $b
b=$(echo | awk "{print sqrt($a)}")
echo $b
b=$(bc <<< "scale=6; sqrt($a)")         #scale=6, which means the result retains 6 decimal places
echo $b
b=$(echo "scale=6; sqrt($a)" | bc)
echo $b
b=`"sqrt($a)"`
echo $b
  • Method
#!bin/bash
echo "Solving the Bivariate Primary Equation ax^2 + bx + c = 0"
read -p "Please enter a: " a
read -p "Please enter b: " b
read -p "Please enter c: " c
echo "The equation you entered is"$a"x^2 + "$b"x + $c = 0"
if [ $a -eq 0 ]
then
  if [ $b -eq 0 ]&&[ $c -ne 0 ]
  then
  echo "The format you entered is incorrect. a,b,c Cannot be equal to 0 at the same time,otherwise x Equal to any number"
  else
  x=`expr $c / $b`
  echo "The equation has only one solution, that is x=-$x"
  fi
else [ $a -ne 0 ]
era=`expr $a \* 2`
b2=`expr $b \* $b`
ac=`expr $a \* $c`
siac=`expr 4 \* $ac`
gx=`expr $b2 - $siac`
if [ $gx -lt 0 ];then echo "unsolvable" && exit 1
fi      
gxj=$(bc <<< "sqrt($gx)")
q=`expr 0 - $b`
fs1=`expr $q + $gxj`
fs2=`expr $q - $gxj`
j1=`expr $fs1 / $era`
j2=`expr $fs2 / $era` 
echo "x1 = $j1 ;x2 = $j2" 
fi
#!/bin/bash
echo please input the number a
read a
echo please input the number b
read b
echo please input the number c
read c
(( d = b*b - 4*a*c))
if [ $a -eq 0 ]
then
(( x = - c/b))
echo the number of x is: $x
elif [ $d -gt 0 ]
then
(( x= a*x*x + b*x +c))
echo the number of x is: $x
else
echo x has no answer
fi

2. For activities in the shopping mall, there are 8% discount on food, 9% discount on daily purchases of 300 yuan and 10,000 discount on clothes. There are three types of goods (named separately)

Requirements: After the program runs, you can choose any commodity category, after entering the commodity category, you can choose which commodity you don't want to buy or buy, after leaving a category, you can also enter the category to purchase.

3. Enter the English words of the day of the week to judge the day of the week

#!/bin/bash
echo "Please enter English words for the week"
read w
case $w in
Monday)
echo "Monday"
;;
Tuesday)
echo "Tuesday"
;;
Wednesday)
echo "Wednesday"
;;
Thursday)
echo "Thursday"
;;
Friday)
echo "Friday"
;;
Saturday)
echo "Saturday"
;;
Sunday)
echo "Sunday"
;;
*)
echo "Input error"
esac

4. Print five characters in reverse order

#!/bin/bash
echo "Please enter five characters separated by spaces"
read a b c d e
echo "$e $d $c $b $a"

5.A 5-digit number to determine if it is palindrome.That is, 12321 is the palindrome number, with 10 digits identical to 10,000 digits.

#!/bin/bash
read -p "Please enter a five digit number" num
w=$(expr $num / 10000)
q=$(expr $num / 1000)
until [ $q -lt 10 ]
do
let q-=10
done
b=$(expr $num / 100)
until [ $b -lt 10 ]
do
let b-=10
done
s=$(expr $num / 10)
until [ $s -lt 10 ]
do
let s-=10
done
g=$num
until [ $g -lt 10 ]
do
let g-=10
done
if [ $w -eq $g ]&&[ $q -eq $s ]
then
echo "$num This number is a palindrome number"
else
echo "$num This number is not palindrome"
fi

summary

1. Structure of case statements

2. Structure of the for statement

3. The structure of the while statement

4. Structure of until statements

5. Array Definition Method

6. shell script debugging methods

aca certification, acp certification

continue

-z Verifies that the location variable is empty, or ||, the brackets are two pairs,

Use source function to load

Job: Make a diamond

Tags: Linux shell Mobile CentOS

Posted on Mon, 02 Dec 2019 06:39:27 -0500 by DJ_CARO