Shell Script Strengthening Exercises

news/2024/10/18 7:51:03/

文章目录

  • 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.

  1. 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.
  2. 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.
  3. Then, we will calculate the semi-perimeter s.
  4. After that, we will use Heron’s formula to calculate the area of the triangle.
  5. 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.

  1. Prompt the user to enter the coefficients a, b, and c of the quadratic equation.
  2. Calculate the discriminant Δ (delta): Δ = b^2 - 4ac.
  3. 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.
  4. Calculate the roots using the quadratic formula: x1 = (-b + sqrt(Δ)) / 2a and x2 = (-b - sqrt(Δ)) / 2a.
  5. 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.

  1. Prompt the user to enter two real numbers a and b.
  2. Compare the size of a and b.
  3. 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.

  1. Prompt the user to enter three real numbers a, b, and c.
  2. Use conditional statements to compare the size of a, b, and c.
  3. 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).

  1. Prompt the user to enter a year.
  2. 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.
  3. 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.

  1. Prompt the user to enter a character.
  2. 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.
  3. 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.

  1. Prompt the user to enter a grade level (A, B, C, D).
  2. 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.

  1. Prompt the user to enter a percentage score.
  2. 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.

  1. Initialize a variable sum to 0 to store the accumulated sum.
  2. Use a for loop to iterate through all even numbers between 2 and 100.
  3. In the loop, add the current even number to the sum variable.
  4. 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.

  1. Initialize a variable product to 1 to store the accumulated product.
  2. Use a for loop to iterate through all even numbers between 2 and 100.
  3. In the loop, multiply the current even number to the product variable.
  4. 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!).

  1. Prompt the user to enter a number greater than 0 and not greater than 10.
  2. Initialize a variable sum to 0 to store the accumulated sum.
  3. Use a for loop to iterate through all integers between 1 and the input number.
  4. In the loop, calculate the factorial of the current integer and add it to the sum variable.
  5. 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

http://www.ppmy.cn/news/581944.html

相关文章

【华为OD机试真题2023 JAVAJS】阿里巴巴找黄金宝箱(IV)

华为OD2023(B卷)机试题库全覆盖,刷题指南点这里 阿里巴巴找黄金宝箱(IV) 知识点数组栈单调栈 时间限制:1s 空间限制:256MB 限定语言:不限 题目描述: 一贫如洗的樵夫阿里巴巴在去砍柴的路上,无意中发现了强盗集团的藏宝地,藏宝地有编号从0~N的箱子,每个箱子上面贴有一…

神秘海域4:盗贼末路特效解密

给公司技术公众号写了篇文章&#xff0c;转到这儿供大家学习。 https://mp.weixin.qq.com/s/K9ijK4Texth_oeEGOQTv4A 版权属公司所有。

如何获得免费的Playstation 3(PS3)

如何获得免费的Playstation 3(PS3)   在PlayStation 3索尼是最畅销的视频游戏控制台他们的第三个版本&#xff0c;但不像其他两个&#xff0c;这一个让你有机会玩网络游​​戏使用PlayStation网络&#xff0c;并使用其内置的WIFI连接至网络冲浪或看电影利用其蓝光光盘播放器。…

ps3自建服务器,PS3新手图文教程之网络设置

PS3新手图文教程之网络设置 在网络上看到 叉烧盒子360写的PS3新手设置指南很不错图文并茂&#xff0c;所以立即联系叉烧盒子360并获得了同意发布于本站&#xff0c;现在将叉烧盒子360写的指南贡献给大家&#xff0c;老手可以跳过了。。。。 经常有许多新手请教网络设置问题&…

【神秘海域】[动图] 面试考查?顺序表 VS 链表:详细对比两者优缺点~

引言 数据结构中有四大线性表结构&#xff1a;顺序表(数组) 、链表 、栈 、队列 在之前的文章中&#xff0c;已经详细介绍过 顺序表(数组) 以及 链表 &#xff0c;思考一下&#xff1a;顺序表(数组) 和 链表 哪一种结构 更优秀 一点呢&#xff1f;都具有什么 优缺点 呢&…

【神秘海域】[动图] 掌握 单链表 只需要这篇文章~ 「超详细」

单链表引言&#x1f419; ❤️‍&#x1f525; 数据结构中有 四大基础结构 &#xff0c;即 四大线性表&#xff1a;顺序表、链表&#x1f47b; 、栈、队列 线性结构逻辑结构图示&#xff1a;顺序表链表栈队列 上一篇文章的内容是&#xff1a;顺序表&#xff0c;从上一篇文章 可…

SSM摄影服务线上选购预约系统-计算机毕设 附源码83784

SSM摄影服务线上选购预约系统 摘 要 随着互联网趋势的到来&#xff0c;各行各业都在考虑利用互联网将自己推广出去&#xff0c;最好方式就是建立自己的互联网系统&#xff0c;并对其进行维护和管理。在现实运用中&#xff0c;应用软件的工作规则和开发步骤&#xff0c;采用SSM技…

【神秘海域】「附代码」数据结构:栈 详解

引言 数据结构中有 四大基础结构 &#xff0c;即 四大线性表&#xff1a;顺序表、链表、栈、队列 被称为线性表是因为&#xff0c;数据用以上四种结构存储&#xff0c;在逻辑结构上都是 在一条线上相邻连续的 线性结构逻辑结构图示&#xff1a;顺序表链表栈队列 前面已经介…