This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!

Why should I learn Shell Programming

  • A Linux o&M engineers need to write shell programs to manage server clusters
  • B for JavaEE and Python programmers, your supervisor will ask you to write some shell scripts for programs or server maintenance, such as writing a script to periodically back up a database
  • C For big data programmers, you need to write shell programs to manage the cluster

02 variable

#!/bin/Bash # case1Let's define the variable A, A=100$echo A=$A echo"A=$A"Case #2Undo variable A unset A echo"A=$A"

a A=`date`A b A=$(date) is equivalent to the backquote # P.S. No Spaces on either side of the equal sign1The variable name can consist of letters, digits, and underscores, but cannot start with a number. 5A=500It is wrong to2No Spaces on either side of the equals sign (note: this is different from the Java syntax for declaring variables)3The variable name is usually uppercaseCopy the code

03 Position parameter variables

#!/bin/bash
echo "0 = $0 1 = $1 2 = $2"
echo "All parameters =$*"
echo "$@"
echo "The number of arguments is $#"
Copy the code

04 operator.

#!/bin/Bash # case1Calculation (:2+3) X4Use the first method: RES1=$(()2+3) *4))
echo "res1=$RES1"RES2=$[()2+3) *4]
echo "res2=$RES2"# Third way RES3=`expr 2 + 3 `
echo "RES3=$RES3"
echo "res4=`expr $RES3 \* 4`"Case #2: Requests the sum of the two arguments [integers] on the command line20 50
SUM=$[$1+ $2] where $1Represents the value of the first argument20 $2Represents the value of the second argument50
echo $SUM
Copy the code

05 Process control

#!/bin/Whether bash # "man" is equal to"man"# Judge statements using =if [ "man" = "man" ]
then
echo "equal"
if [ 23‐ ge22 ]
then
echo "More than"
else
echo "Less than"
fi
Copy the code
‐f: /root/shcode/aaa.txt: /root/shcode/aaa.txt: /root/shcode/aaa.txt: /root/shcode/aaa.txtif‐ echo. [‐f /root/shcode/aaa.txt] then echo"There"
else
echo "Nonexistent"
fi
Copy the code

Flow control statement

Case statements and if… elif… The else statement is a multi-branch condition, but unlike the if multi-branch condition, the case statement can only determine one conditional relationship, whereas the if statement can determine multiple conditional relationships.

For loop of flow control

# Basic syntax1:forvariablein123..do
echo "On Monday"
;;
"2")
echo "Tuesday"
;;
"3")
echo "On Wednesday"
;;
"4")
echo "Thursday"
;;
"5")
echo "Friday"
;;
"6")
echo "Saturday"
;;
"Seven")
echo "Sunday"
;;
*)
echo "You entered something wrong.";; Esac program/code done # basic syntax2:

for(initial value; Circulation control conditions; Variable change)doProcedures are doneCopy the code
#!/bin/Bash # case1Print the arguments entered on the command line. #$* treats the arguments entered as a wholefor i in "$*"
do
echo "num is $i"Done # uses $@ to retrieve the input arguments. Note that this is treated separately, so each argument outputs several echo sentences"= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ="
for j in "$@"
do
echo "num is $j"
done
Copy the code

07 Flow control of while loop

whileLoop basic syntaxwhile[Conditional expression]doProcedure done note:whileThere is space between and [, as well as between conditions and [Copy the code
#!/bin/Bash # case1: Enter a number n from the command line for statistics1+2+... What is the value of plus n? SUM is equal to0
i=0
while [ $i ‐le $1 ]
doSUM = $[$SUM + $I] or written SUM = $(($SUM + $I)) # I since I = $increasing [$I +1] or I =$(($I +1 ))
done
echo $SUM =$SUM
Copy the code

08 Read Reads console input

#!/bin/Bash # case1Read a num1 value entered by the console read ‐p"Please enter a number NUM1=" NUM1
echo "You enter NUM1=$NUM1"Case #2Read console input for a num2 value in10Input read ‐t in seconds10‐ p"Please enter a number NUM2=" NUM2
echo "You typed NUM2=$NUM2"
Copy the code

09 function

#!/bin/Bash # calculates the sum of the input two arguments, and getSum # defines the function getSumfunction getSum() {
SUM=$[$n1+$n2]
echo "And is = $SUM"} # Input two values read ‐p"Please enter a number n1="N1 read ‐ p"Please enter a number n2="N2 # call getSum $n1 $n2Copy the code

09 random number

echo $[$RANDOM%3#] produce0-3Echo $[$RANDOM%4#] produce1-50Between $[$RANDOM%50+1[$RANDOM%50The resulting number is0-49# produce10-99Between $[$RANDOM%89+10]
Copy the code

So let’s practice with a couple of problems.

exercises

The first question

Write a shell script to do the following

1 Display text “Hello, ReagnYue”

2 Define a variable STR with an initial value of “hello” and redirect the output to /home/str.txt

3 Obtain the parameter n. 1+2+3+… And of + n

#!/bin/bash

echo "Hello, ReganYue."
STR="hello"
echo STR >> /home/str.txt
sum=0
for i in $(seq $1)
do
sum=$((sum+i))
done
echo sum=$sum
Copy the code

The second question

Write a shell script to do the following

In terminal 1 to enter a score between 1-100, if the result is greater than or equal to 90 and less than 100, according to “excellent”, if the result is greater than or equal to 70 and less than 90, according to “good”, should the scores greater than 60 and less than 70, according to pass, if the result is greater than or equal to zero and less than 60, according to “less than”, enter a different value, “Input error” is displayed.

2 Pass a parameter to the script. If the parameter is exit, the script will display “exit program”. If the parameter is yes, the script will display “Continue”.

#!/bin/bash

read -p "Please enter the result:" score
if [ $score -ge 90 -a $score -lt 100 ]
then
echo "Good"
elif [ $score -ge 70 -a $score -lt 90 ]
then
echo "Good"
elif [ $score -ge 60 -a $score -lt 70 ]
then
echo "Pass"
elif [ $score -ge 0 -a $score -lt 60 ]
then
echo "Fail"
else
echo "Input error"
fi

if[$1 = "exit" ]
then
echo "Exit program"
elif [ $1 = "yes" ]
then
echo "Continue"
else
echo "Input error"
fi

Copy the code

The third question

Write a shell script to do the following

1 Obtains the two numbers entered by the user and displays the larger number of the two numbers

2 Add a new group named class01, and then add 30 users belonging to this group. The user name is stdXX, where XX ranges from 01 to 30

#!/bin/bash

read -p "Please enter two numbers:" a b

if [ $a -gt $b ]
then
echo "$a"
fi

if [ $b -gt $a ]
then
echo "$b"
fi

group="class01"
groupadd $group
i=1
while [ $i -le 30 ]
do
if [ $i -le 9 ]
then
username=user0$i
else
username=user$i
fi
useradd $username
mkdir /home/$username
chown -R $username /home/$username
chgrp -R $group /home/$username
usermod -g $group $username
i=$(($i+1))
done

Copy the code

The fourth question

Write a shell script to do the following

1 In the root directory, create a folder code, create a phonenum. TXT file in the code folder, and write a script to randomly generate 1000 phone numbers starting with 158, and add each line to the phonenum

2 Draw 5 lucky viewers in the 1000 mobile phone numbers above, show the 5 lucky viewers, display the requirements of the mobile phone number is only to show the first three numbers and the end of the four numbers in the middle are replaced by 158***4589

#!/bin/bash
cd /root
mkdir code
touch phonenum.txt

for i in {1.1000.};
do
a1=$(($RANDOM%10))
a2=$(($RANDOM%10))
a3=$(($RANDOM%10))
a4=$(($RANDOM%10))
a5=$(($RANDOM%10))
a6=$(($RANDOM%10))
a7=$(($RANDOM%10))
a8=$(($RANDOM%10))
echo "158$a1$a2$a3$a4$a5$a6$a7$a8" >>  /root/code/phonenum.txt
done

Copy the code

The fifth problem

Write a shell script to do the following

Create 50 directories under /userdata, that is, user1 to user50, and set the permission for each directory. The permission for other users is read. The permissions of the file owner are read, write, and execute. The permissions of the group to which the file owner belongs are read and execute.

#!/bin/bash

for i in {1.. 50};
do
mkdir "user$i"
chmod 754 "user$i"
done

Copy the code