Summary of shell script writing on October 30, 2021

Posted by idevlin on Sun, 31 Oct 2021 07:48:53 +0100

Summarize the scripting from 10.14 to 10.28

In order to consolidate the relevant knowledge points of shell script, the problems and solutions encountered in writing script are summarized.
Title I
10.14.sh
The logic is not perfect, and there is no troubleshooting experiment.
Many problems will arise when troubleshooting experiments are carried out:
1. The user name is registered and added before confirming whether the information is correct
2. Password display, insecure

#!/bin/bash
#Date:2021.10.14
#Autor:YYX
#name: register user system
echo "welcome to world!"
read -p  "Please enter user name: "  name 
useradd "$name"
if
	[ $? != 0 ]
then
	exit 0
else	
#Set password      
#Judge password composition
if grep '^[[:alnum:]]' <<< "$mima"
then
	read -p "please ensure your password:" mima2
else
	echo "The password entered is illegal. Please re-enter it"
	exit 0
fi
#
echo "$mima" | passwd --stdin "$name" &> /dev/null

if [ $mima = $mima2 ]
then
	echo "login was successful!" #You have successfully registered
else
	echo "Password confirmation failed, please confirm again" #Your password is incorrect. Please register again
fi

Title II

#!/bin/bash
#date: 10.20
#Autor: yyx
#name: registered user
#enter one user name
echo "Set the user name, consisting of alphanumeric characters, with a length of 6-10 between"
read -p "Please set user name:" name1
if grep '^[[:alnum:]]' <<< "$name1"
then
	echo "The user name is legal"
	len1=`echo ${#name1}`
	if [ $len1 -gt 5 -a $len1 -lt 11 ]
	then
		echo "The length of user name is legal"
	else
		echo "Illegal user name length"
		exit 0
	fi
else
	echo "Illegal user name"
	exit 0
fi
echo "Your username is $name1,Please judge whether it is correct"
read -p "Please determine whether the user name is correct and enter( Y/N): " panduan
case "$panduan" in
	Y|y)
	echo "The user name is correct!"
	;;
	N|n)
	echo "User name error!"
	exit 0
	;;
	*)
	echo "Illegal input character"
	exit 0
esac

#Set password
echo "Set the password, consisting of numbers and letters, with a length of 6-10 between"
read -s -p "Please set the password: " passworld1
if grep '^[[:alnum:]]' <<< "$passworld1"
then
	echo "The password is legal"
	len2=`echo ${#passworld1}`
	if [ $len2 -gt 5 -a $len2 -lt 11 ]
	then
		echo "The password length is legal"
		read -s -p  "Please enter the password again: " passworld2
		if [ $passworld1 = $passworld2 ]
		then
			echo "The password has been confirmed"
			useradd "$name1"
			if [ $? != 0 ]
			then
				echo "This user name exists, please add another user name again"
				exit 0
			else
				echo "Registration succeeded!"
			fi
		else
			echo "The passwords do not match. Please try again"
		exit 0
		fi

	else
		echo "Illegal password length, please try again!"
	exit 0
	fi
else
	echo "Illegal password"
	exit 0
fi

Compared with Item 1, it is improved and logically clearer than item 1. User registration is divided into two parts. User part: judge the composition of user name, judge the length of user name and confirm the information of user name; password part: input of password, judge the composition of password, judge the length of password and confirm the password. Use u after these are executed Use the seradd command to add the user name.

shell knowledge points used

1. read instruction

read -p: input instructions from the keyboard and assign values to variables to realize the interaction between the system and users.
Introduction to relevant parameters:
-p: Displays a prompt on the screen
-s: Do not display any input interrupted

[root@slave_server ~]# read -p 'please enter a number:' num
 Please enter a number: 1
[root@slave_server ~]# echo $num
1

Note: when adding the - s option, you need to put the - S parameter before - p, otherwise an error will be reported

[root@slave_server ~]# read -s -p 'print the world: ' world
print the world: [root@slave_server ~]# 
[root@slave_server ~]# echo $world
haha
[root@slave_server ~]
2. Conditional judgment statement if

if syntax introduction

if Conditional judgment statement 1
then	#If the conditions are met, the statement is executed
elif Conditional judgment statement 2
then	#Statement that meets condition 2
else
	Execute statement	#If conditional statements 1 and 2 are not met, execute the statement
fi	#Terminator of conditional judgment statement
3. Multi condition judgment statement -- case statement

This statement is used to judge the sentence that meets the conditions. If it meets a certain condition, it will be executed

read -p "print the bl: " bl
case "$bl" in	#If the value of matching bl matches that condition, the statement corresponding to that condition is executed
	Y|y)
	echo "The user name is entered correctly!"	#When the variable value is y or Y, "output user name input is correct"
	;;
	N|n)
	echo "User name error!"	#When the variable value is n or N, "output user name error" and exit the script
	exit 0
	;;
	*)
	echo "Illegal input character"	#When the variable value is other values (except Y/y and N/n), output "illegal input character" and exit the script
	exit 0
esac #The terminator of the multi condition judgment statement

4. Related use of regular expressions
The matching variable (name) is alphanumeric.

grep '^[[:alnum:]]' <<< "$name"

5. Calculate the character length of the variable (password)

${#password}

6. Application of relational operators
-eq: equal to
-lt, - le: less than
-gt, - ge: greater than
-a: And
-ne: unequal
!: non operation
-o: Or operation
-a: And operation

a=3
b=5
#Judge whether a and b are equal
if [ $a -eq $b ]
#Note: when judging the relationship between two variables, there should be spaces between square brackets and variables, and between variables and judges.
then
	echo "equal"
else
	echo "Unequal"
fi

Title III
Write a calculator that converts degrees Celsius to degrees Fahrenheit

#!/bin/bash
#Data:10.16
#Autor:yyx
#name:Temperature converter
#Formula: celcius*1.8+32=fahrenheit
read -p "Please input celcius: " celcius

if grep '^[[:digit:]]' <<< "$celcius"
then
	echo "Please continue"

else
	echo "Illegal character"
	echo "Please enter a positive integer!"
	exit 0
fi
fahrenheit=`echo "$celcius 1.8 32" | awk '{print ($1*$2)+32}'`
	echo $celcius celsius is $fahrenheit fahrenheit

shell knowledge points used
1. Regular expressions are used to match variables (celcius)

grep '^[[:digit:]] <<< "$celicus"

2,awk

Title IV
Calculate the volume and bottom area of the cylinder

#!/bin/bash
#Title: write a program to read the radius and height of the cylinder and calculate the bottom area of the cylinder using the following formula
#area = radius * radius * pai
#volume = area * length
read -p "Please enter the radius of the cylinder:" radius
if grep '^[[:digit:]||[:digit:].[:digit:]]' <<< "$radius"
then
	read -p "Please enter the height of the cylinder:" length
	if grep '^[[:digit:]||[:digit:].[:digit:]]' <<< "$length"
	then
		pi=3.14
           	area=`echo "$radius*$radius*$pi" | bc`
		echo "The bottom area of the cylinder is $area"
		volume=`echo "$area*$length " | bc`
		echo "The volume of the cylinder is $volume"
	else
		echo "illegal'high',Please do it again!"
	fi

else
	echo "'radius'Illegal, please do it again!"
fi

shell knowledge points used
1. Match positive integers and decimals

grep '^[[:digit:] || [:digit:].[:digit:]]'

2. Decimal operation with bc

pi=3.14	#The PI is defined as 3.14
area=`echo "$radius*$radius*$pi" | bc`  #area=radius*radius*pi
#An operation in which an expression is caused by double quotation marks and bc is connected by a pipe character. There is no space between variables in the expression.

Title V
Calculate the sum of each bit of a three digit number

#Enter a three digit number and find the sum of the numbers
read -p 'Please enter a 3-digit number:' num
grep '^[[:digit:]]' <<< $num &> /dev/null
sz=`echo $?`
if [ $sz == 0 ]
then
	len=`echo ${#num}`
	if [ $len == 3 ]
	then
		bai=`expr $num / 100`
		shi=`expr $num / 10`
		ge=`expr $num % 100`
	        sum=`expr $bai + $shi + $ge`
		echo $num Is a three digit integer, and the sum of each digit is $sum
	else
		echo 'Illegal character length, please re-enter'
		exit 0	
	fi
else
	echo 'Illegal character, please re-enter'
	exit 0
fi

1. The output is not displayed on the screen

grep '^[[:digit:]]' <<< $num &> /dev/null  #Filter whether the num variable is a number and do not display the result to the screen (throw the result to / dev/null)
# /dev/null represents an empty device file. Transferring the display to this is equivalent to permanently deleting the prompt information

2. Application of exit status code
The exit status code is an integer, ranging from 0 to 255.
0 means the command is successful, and non-0 means the command is unsuccessful
$?: exit status code of the previous command or function

num=123
grep '^[[:digit:]]' <<< $num &> /dev/null	#Filter whether there are numbers in the num variable (num=123)
echo $? #Print the exit code of the last command
0	#The exit code is 0, which means that the num variable is composed of numbers

num=..0
grep '^[[:digit:]]' <<< $num &> /dev/null	#Filter whether there are numbers in the num variable (num=..0)
echo $?
1	#At this time, if the exit code is non-0, it can be judged that the composition of num variable is more than just numbers

3. Operation of variables (arithmetic operators)

+expr $a + $b
-expr $a - $b
*expr $a \* $b
/expr $b / $a
%expr $b % $a
=assignment
==[$a == $b] equal, used to compare whether two numbers are equal.
!=[$a! = $b] not equal, used to compare two numbers
#Calculate each digit of a hundred digit
  bai=`expr $num / 100` #Note: during operation, expr(expr) is an expression calculation tool, which causes an expression with backquotes, and there should be spaces before and after the operator
  shi=`expr $num / 10`
  ge=`expr $num % 100`
  sum=`expr $bai + $shi + $ge`

Title VI
Minute Conversion

#!/bin/bash
read -s -p 'Please enter a number:' num
year_min=`expr 24 \* 60 \* 365` #Minutes of a year
day_min=`expr 24 \* 60`
hour_min=60
min=`echo $num`
if grep '^[[:digit:]]' <<< $num
then
	if [ $num -gt $day_min -a $num -lt $year_min ]
	then
		day=`expr $num / $day_min`
		hour_min=`expr $num % $day_min`
		hour=`expr $hour_min / 60`
		min=`expr $num - $year_min - $day_min - $hour_min`
		echo Time is $day day $hour hour $min minute
	elif [ $num -gt $hour_min -a $num -lt $day_min ]
	then
		echo Time is $hour hour $min minute
	elif [ $num -lt $hour_min ]
	then
		echo Time is $min minute
	else
		echo Time is $year year $day day $hou hour $min minute
	fi
else
	echo 'The character you entered is illegal. Please try again'
exit 0
fi

shell related knowledge
1. Variable assignment
If you want to assign the execution result of a command to a variable, you need to enclose the instruction in backquotes

year_min=`expr 24 \* 60 \* 365` #The number of minutes in a year and assign the calculation result to the variable
```+


Topics: shell Vmware bash