文章目录
- 1、Given the lengths of the three sides a, b, and c of a triangle, use a formula to calculate the area of the triangle.
- 2、Use the quadratic formula to find the two roots of a quadratic equation, with a, b, and c entered from the keyboard.
- 3、Input two real numbers a and b, and output them in ascending order by value.
- 4、Input three real numbers a, b, and c, and output them in ascending order by value.
- 5、Write a program to determine whether a given year is a leap year (Note: If the year is not a multiple of 100 and is a multiple of 4, it is a leap year; if the year is a multiple of 100 and is a multiple of 400, it is a leap year).
- 6、Input a character, determine whether it is an uppercase letter, if so, convert it to a lowercase letter, if not, do not convert, and then output the final obtained character.
- 7、Write a program using a case statement to convert a course grade originally in A, B, C, D levels to a percentage score. The rules are: A level is converted to 85 ~ 100; B is 70 ~ 84; C is 60 ~ 69; D is less than 60. The grade level is entered from the keyboard, and the score range is output.
- 8、The original score of a course is in percentage. Now it needs to be converted to a grade level. The rules are: above 90 is A, 80 ~ 90 is B, 70 ~ 79 is C, 60 ~ 69 is D, and below 60 is E.
- 9、Calculate the sum of the series 2+4+6+...+100.
- 10、Calculate the product of the series `2*4*6*8*...*100`.
- 11、Input a number greater than 0 and not greater than 10, and calculate the cumulative product (e.g., if the input number is 5, calculate 1!+2!+3!+4!+5!).
- 12、Output integers between 100 and 300 (inclusive) that are not divisible by 4.
- 13、Reverse Output
- 14、Create New Users
- 15、Check if User Exists and Determine if They Are a Superuser
- 16、Create or Directory File
- 17、Test if IP is Reachable
- 18、Script to Output Machine Information
1、Given the lengths of the three sides a, b, and c of a triangle, use a formula to calculate the area of the triangle.
- First, we need to check if the user provided three side lengths as arguments. If not provided, we will prompt the user to provide three side lengths and exit the script.
- Next, we need to check if the provided side lengths form a valid triangle. We will use the triangle inequality theorem (the sum of any two sides is greater than the third side) to verify. If the condition is not met, we will inform the user that the provided side lengths cannot form a valid triangle and exit the script.
- Then, we will calculate the semi-perimeter s.
- After that, we will use Heron’s formula to calculate the area of the triangle.
- Finally, we will print the area of the triangle.
#!/bin/bash# Check if the user provided three side lengths as arguments
if [ $# -ne 3 ]; thenecho "Please provide three side lengths as arguments."exit 1
fia=$1
b=$2
c=$3# Check if the provided side lengths form a valid triangle
if [ $(echo "$a + $b <= $c" | bc) -eq 1 ] || [ $(echo "$a + $c <= $b" | bc) -eq 1 ] || [ $(echo "$b + $c <= $a" | bc) -eq 1 ]; thenecho "The provided side lengths do not form a valid triangle."exit 1
fi# Calculate the semi-perimeter
s=$(echo "($a + $b + $c) / 2" | bc -l)# Calculate the area using Heron's formula
area=$(echo "sqrt($s * ($s - $a) * ($s - $b) * ($s - $c))" | bc -l)# Print the area of the triangle
echo "The area of the triangle is $area."
2、Use the quadratic formula to find the two roots of a quadratic equation, with a, b, and c entered from the keyboard.
- Prompt the user to enter the coefficients a, b, and c of the quadratic equation.
- Calculate the discriminant Δ (delta): Δ = b^2 - 4ac.
- Determine the root situation of the equation based on the value of the discriminant:
- If Δ > 0, the equation has two unequal real roots.
- If Δ = 0, the equation has two equal real roots (one real root).
- If Δ < 0, the equation has no real roots.
- Calculate the roots using the quadratic formula: x1 = (-b + sqrt(Δ)) / 2a and x2 = (-b - sqrt(Δ)) / 2a.
- Output the roots of the equation.
#!/bin/bash# Prompt the user to enter the coefficients a, b, and c
echo "Please enter the coefficients a, b, and c of the quadratic equation:"
read a
read b
read c# Calculate the discriminant
delta=$(echo "$b^2 - 4 * $a * $c" | bc)# Determine the root situation and calculate the roots
if [ $(echo "$delta > 0" | bc) -eq 1 ]; thenx1=$(echo "(-$b + sqrt($delta)) / (2 * $a)" | bc -l)x2=$(echo "(-$b - sqrt($delta)) / (2 * $a)" | bc -l)echo "The equation has two unequal real roots: x1 = $x1, x2 = $x2"
elif [ $(echo "$delta == 0" | bc) -eq 1 ]; thenx=$(echo "(-$b) / (2 * $a)" | bc -l)echo "The equation has two equal real roots (one real root): x = $x"
elseecho "The equation has no real roots."
fi
3、Input two real numbers a and b, and output them in ascending order by value.
- Prompt the user to enter two real numbers a and b.
- Compare the size of a and b.
- Output a and b in ascending order.
#!/bin/bash# Prompt the user to enter two real numbers a and b
echo "Please enter two real numbers a and b:"
read a
read b# Compare the size of a and b and output them in ascending order
if [ $(echo "$a < $b" | bc) -eq 1 ]; thenecho "The numbers in ascending order are: $a, $b"
elseecho "The numbers in ascending order are: $b, $a"
fi
4、Input three real numbers a, b, and c, and output them in ascending order by value.
- Prompt the user to enter three real numbers a, b, and c.
- Use conditional statements to compare the size of a, b, and c.
- Output a, b, and c in ascending order.
#!/bin/bash# Prompt the user to enter three real numbers a, b, and c
echo "Please enter three real numbers a, b, and c:"
read a
read b
read c# Compare the size of a, b, and c and output them in ascending order
if [ $(echo "$a < $b" | bc) -eq 1 ]; thenif [ $(echo "$b < $c" | bc) -eq 1 ]; thenecho "The numbers in ascending order are: $a, $b, $c"elseif [ $(echo "$a < $c" | bc) -eq 1 ]; thenecho "The numbers in ascending order are: $a, $c, $b"elseecho "The numbers in ascending order are: $c, $a, $b"fifi
elseif [ $(echo "$a < $c" | bc) -eq 1 ]; thenecho "The numbers in ascending order are: $b, $a, $c"elseif [ $(echo "$b < $c" | bc) -eq 1 ]; thenecho "The numbers in ascending order are: $b, $c, $a"elseecho "The numbers in ascending order are: $c, $b, $a"fifi
fi
5、Write a program to determine whether a given year is a leap year (Note: If the year is not a multiple of 100 and is a multiple of 4, it is a leap year; if the year is a multiple of 100 and is a multiple of 400, it is a leap year).
- Prompt the user to enter a year.
- Use conditional statements to determine whether the year is a leap year:
- If the year is not a multiple of 100 and is a multiple of 4, it is a leap year.
- If the year is a multiple of 100 and is a multiple of 400, it is a leap year.
- Output the result, indicating whether the given year is a leap year.
#!/bin/bash# Prompt the user to enter a year
echo "Please enter a year:"
read year# Determine whether the year is a leap year
if [ $((year % 4)) -eq 0 ] && [ $((year % 100)) -ne 0 ] || [ $((year % 400)) -eq 0 ]; thenecho "The year $year is a leap year."
elseecho "The year $year is not a leap year."
fi
6、Input a character, determine whether it is an uppercase letter, if so, convert it to a lowercase letter, if not, do not convert, and then output the final obtained character.
- Prompt the user to enter a character.
- Use conditional statements to determine whether the character is an uppercase letter:
- If the character is an uppercase letter, convert it to a lowercase letter.
- If the character is not an uppercase letter, keep it unchanged.
- Output the final obtained character.
#!/bin/bash# Prompt the user to enter a character
echo "Please enter a character:"
read -n 1 char
echo# Determine whether the character is an uppercase letter and convert it if necessary
if [[ $char =~ [A-Z] ]]; thenchar=$(echo "$char" | tr 'A-Z' 'a-z')
fi# Output the final obtained character
echo "The final character is: $char"
7、Write a program using a case statement to convert a course grade originally in A, B, C, D levels to a percentage score. The rules are: A level is converted to 85 ~ 100; B is 70 ~ 84; C is 60 ~ 69; D is less than 60. The grade level is entered from the keyboard, and the score range is output.
- Prompt the user to enter a grade level (A, B, C, D).
- Use a switch statement to output the corresponding score range based on the input grade level.
#!/bin/bash# Prompt the user to enter a grade level
echo "Please enter a grade level (A, B, C, D):"
read grade# Use a case statement to output the corresponding score range based on the input grade level
case $grade inA)echo "The score range is 85 ~ 100.";;B)echo "The score range is 70 ~ 84.";;C)echo "The score range is 60 ~ 69.";;D)echo "The score range is less than 60.";;*)echo "Invalid grade level. Please enter A, B, C, or D.";;
esac
8、The original score of a course is in percentage. Now it needs to be converted to a grade level. The rules are: above 90 is A, 80 ~ 90 is B, 70 ~ 79 is C, 60 ~ 69 is D, and below 60 is E.
- Prompt the user to enter a percentage score.
- Use conditional statements to output the corresponding grade level based on the input percentage score.
#!/bin/bash# Prompt the user to enter a percentage score
echo "Please enter a percentage score:"
read score# Use conditional statements to output the corresponding grade level based on the input percentage score
if [ $score -ge 90 ]; thenecho "The grade level is A."
elif [ $score -ge 80 ]; thenecho "The grade level is B."
elif [ $score -ge 70 ]; thenecho "The grade level is C."
elif [ $score -ge 60 ]; thenecho "The grade level is D."
elseecho "The grade level is E."
fi
#!/bin/bash# Prompt the user to enter a percentage score
echo "Please enter a percentage score:"
read score# Use a case statement to output the corresponding grade level based on the input percentage score
case 1 in$(($score >= 90)))echo "The grade level is A.";;$(($score >= 80 && $score < 90)))echo "The grade level is B.";;$(($score >= 70 && $score < 80)))echo "The grade level is C.";;$(($score >= 60 && $score < 70)))echo "The grade level is D.";;*)echo "The grade level is E.";;
esac
9、Calculate the sum of the series 2+4+6+…+100.
- Initialize a variable sum to 0 to store the accumulated sum.
- Use a for loop to iterate through all even numbers between 2 and 100.
- In the loop, add the current even number to the sum variable.
- Output the final accumulated sum.
#!/bin/bash# Initialize the sum variable
sum=0# Iterate through all even numbers between 2 and 100
for ((i=2; i<=100; i+=2)); dosum=$((sum + i))
done# Output the final accumulated sum
echo "The sum of the series 2+4+6+...+100 is: $sum"
10、Calculate the product of the series 2*4*6*8*...*100
.
- Initialize a variable product to 1 to store the accumulated product.
- Use a for loop to iterate through all even numbers between 2 and 100.
- In the loop, multiply the current even number to the product variable.
- Output the final accumulated product.
#!/bin/bash# Initialize the product variable
product=1# Iterate through all even numbers between 2 and 100
for ((i=2; i<=100; i+=2)); doproduct=$((product * i))
done# Output the final accumulated product
echo "The product of the series 2*4*6*8*...*100 is: $product"
11、Input a number greater than 0 and not greater than 10, and calculate the cumulative product (e.g., if the input number is 5, calculate 1!+2!+3!+4!+5!).
- Prompt the user to enter a number greater than 0 and not greater than 10.
- Initialize a variable sum to 0 to store the accumulated sum.
- Use a for loop to iterate through all integers between 1 and the input number.
- In the loop, calculate the factorial of the current integer and add it to the sum variable.
- Output the final accumulated sum.
#!/bin/bash# Prompt the user to enter a number greater than 0 and not greater than 10
echo "Please enter a number greater than 0 and not greater than 10:"
read num# Initialize the sum variable
sum=0# Iterate through all integers between 1 and the input number
for ((i=1; i<=num; i++)); dofactorial=1# Calculate the factorial of the current integerfor ((j=1; j<=i; j++)); dofactorial=$((factorial * j))done# Add the factorial to the sum variablesum=$((sum + factorial))
done# Output the final accumulated sum
echo "The sum of the factorials is: $sum"
12、Output integers between 100 and 300 (inclusive) that are not divisible by 4.
To solve this problem, we can iterate through the numbers between 100 and 300, and check if each number is not divisible by 4. If it is not divisible by 4, we can output the number.
#!/bin/bash
for i in {100..300}; doif [ $((i % 4)) -ne 0 ]; thenecho $ifi
done
13、Reverse Output
- If the user inputs “yes”, display “no”.
- If the user inputs “no”, display “yes”.
- If the user inputs anything else, prompt the user to input “yes” or “no”.
- Ignore case sensitivity.
To solve this problem, we can read the user input, convert it to lowercase, and then use conditional statements to check the input and display the corresponding output.
#!/bin/bash
read -p "Please enter 'yes' or 'no': " input
input_lower=$(echo "$input" | tr '[:upper:]' '[:lower:]')case $input_lower in"yes")echo "no";;"no")echo "yes";;*)echo "Please input 'yes' or 'no'";;
esac
14、Create New Users
- Create a username list called “namefile”.
- Create a script that can automatically create users based on the “namefile” and generate random passwords. After the user is created, import the username and password into /root/loginname.txt.
- To generate a random password, you can use: openssl rand -base64 6
To solve this problem, we can read the “namefile” line by line, create a user for each line, generate a random password using the “openssl” command, and then append the username and password to the /root/loginname.txt file.
#!/bin/bash
namefile="namefile.txt"while read -r username; doif id -u "$username" >/dev/null 2>&1; thenecho "User $username already exists"elsepassword=$(openssl rand -base64 6)useradd -m "$username"echo "$username:$password" | chpasswdecho "User $username created with password: $password"echo "$username:$password" >> /root/loginname.txtfi
done < "$namefile"
15、Check if User Exists and Determine if They Are a Superuser
- Write a script that checks if a specified user exists. If the user exists, display that they exist, show their user ID and shell, and determine if they are a superuser. If the user does not exist, create the user and display their user ID.
To solve this problem, we can use the id
command to check if the user exists, and if they do, display their user ID and shell using the getent
command. We can then check if the user is a superuser by examining their user ID. If the user does not exist, we can create the user using the useradd
command and display their user ID.
#!/bin/bash
read -p "Enter the username: " usernameif id -u "$username" >/dev/null 2>&1; thenecho "User $username already exists"user_id=$(id -u "$username")user_shell=$(getent passwd "$username" | cut -d: -f7)echo "User ID: $user_id"echo "User Shell: $user_shell"if [ "$user_id" -eq 0 ]; thenecho "$username is a superuser"elseecho "$username is not a superuser"fi
elseuseradd -m "$username"user_id=$(id -u "$username")echo "User $username created with User ID: $user_id"
fi
This script reads the username, checks if the user exists using the id
command, and if they do, displays their user ID and shell using the getent
command. It then checks if the user is a superuser by examining their user ID. If the user does not exist, it creates the user using the useradd
command and displays their user ID.
16、Create or Directory File
- The script should have interactive functionality.
- The script is used to backup system directories.
- Prompt the user to input a directory or filename.
- Check if the file the user wants to backup exists. If it does not exist, inform the user and output the corresponding error.
- Check if the target directory for the backup exists. If the directory does not exist, ask the user if they want to create it. If the directory already exists, ask the user if they want to rename it.
To solve this problem, we can use the read
command to interact with the user, and use conditional statements to check if the file and target directory exist. We can then ask the user for their desired action and perform the corresponding operation.
#!/bin/bash
read -p "Enter the file or directory you want to backup: " source
read -p "Enter the target backup directory: " targetif [ ! -e "$source" ]; thenecho "Error: The file or directory $source does not exist"exit 1
fiif [ ! -d "$target" ]; thenread -p "The target directory $target does not exist. Do you want to create it? (y/n): " createif [ "$create" = "y" ]; thenmkdir -p "$target"elseexit 1fi
elseread -p "The target directory $target already exists. Do you want to rename it? (y/n): " renameif [ "$rename" = "y" ]; thenread -p "Enter the new target directory name: " new_targetmv "$target" "$new_target"target="$new_target"fi
ficp -r "$source" "$target"
echo "Backup of $source to $target completed"
This script reads the source file or directory and target directory from the user, checks if the source exists, and if the target directory exists or needs to be created or renamed. It then performs the corresponding operations and copies the source to the target directory.
17、Test if IP is Reachable
- Based on the IP addresses listed in the iplist.txt file, determine if the IP addresses are reachable.
- Only display reachable IP addresses. (Unreachable IP addresses can be redirected to /dev/null)
To solve this problem, we can read the iplist.txt file line by line, and use the ping
command to check if each IP address is reachable. If the IP address is reachable, we can display it.
#!/bin/bash
iplist="iplist.txt"while read -r ip; doping -c 1 -W 1 "$ip" > /dev/null 2>&1if [ $? -eq 0 ]; thenecho "IP $ip is reachable"fi
done < "$iplist"
#!/bin/bash
#This is a shell script for checking the ip is arrive or not
file=$(cat ./iplist.txt)
for i in $file
doping -c1 -w1 $i &> /dev/null && echo "$i is up" || echo "$i is down"
done
~
#!/bin/bash
for i in {1..255}
doping -c1 -w1 192.168.30.$i &> /dev/null && echo -e "\033[032m 192.168.30.$i is up \033[0m" || echo -e "\033[031m 192.168.30.$i is down \033[0m"
done
18、Script to Output Machine Information
- Extract the IP address and MAC address of the local machine’s network card and output it to /root/nic.
- Extract the local machine’s disk usage and output it to /root/disk.
- Check the system space usage, and if the usage of the root (/) partition is greater than 30%, delete the contents of /tmp.
To solve this problem, we can use various commands to extract the required information, such as ip
, awk
, df
, and rm
. We can then output the information to the specified files and perform the necessary actions based on the system space usage.
#!/bin/bash
ip -o link show | awk '{print $2, $17}' > /root/nic
df -h | grep -E 'Filesystem|/dev' > /root/diskroot_usage=$(df -h / | awk 'NR==2 {print $5}' | tr -d '%')
if [ "$root_usage" -gt 30 ]; thenrm -rf /tmp/*echo "Deleted contents of /tmp due to root partition usage exceeding 30%"
fi
This script uses the ip
and awk
commands to extract the IP and MAC addresses of the local machine’s network card and outputs it to /root/nic. It then uses the df
command to extract the disk usage and outputs it to /root/disk. Finally, it checks the system space usage and deletes the contents of /tmp if the root partition usage is greater than 30%.
#!/bin/bash
# This shell script is for monitoring diskUsage&IP&MAC
MAC=`ip addr | awk NR==8 | awk '{print $2}'`
IP=`ifconfig | grep -E "\<([0-9]{1,3}\.){3}([0-9]{1,3})\>" | grep -v 127.0.0.1 | awk '{print $2}'` # Cannot handle the selection of multiple network card addresses
DiskUsage=`df -h | grep -v Filesystem | awk '{print $1,$5}'` # List partitions and partition usage rates
RootZoneUsage=`df -h | grep sda | awk '{print $5}'` # List the root partition usage rate
echo "$IP $MAC" > /root/nic # Write IP and MAC addresses to a file
echo "$DiskUsage" > /root/disk # Write partition usage rates to a file
echo "$RootZoneUsage" > ./file # Write the root partition usage rate to an existing file using a relative path
RootUsage=`sed 's/%//g' ./file` # Use sed to filter out the percentage sign from the usage rate
if [ $RootUsage -gt 30 ] # The most troublesome line, comparing usage rates, but -lt -gt cannot use percentage comparison, so the percentage is treated as a whole number
thencat /dev/null > /tmp/
elseecho "The Disk Usage is less than 30%, you do not need care "
fi