Hey DevCloud Ninjas! π Time for a fun Bash scripting challenge that'll help you level up your cloud skills! π
Your mission, should you choose to accept it, is to create a Bash script called vm_info.sh
that gives us some basic info about our virtual machine. Here's what I want you to do:
-
Create a script that does the following:
- Prints a welcome message
- Checks and displays the number of CPU cores
- Shows the total amount of RAM
- Displays the available disk space
- Lists the top 3 processes using the most CPU
-
Use if-else statements to:
- Check if the user running the script is root
- If they are, print a warning message
-
Implement a simple while loop that:
- Asks the user if they want to see current CPU usage
- If yes, show the CPU usage every 5 seconds until the user presses Ctrl+C
- If no, exit the script with a goodbye message
Here's a template to get you started:
#!/bin/bash
echo "Welcome to VM Info Script!"
# Your code here
echo "Script finished. Keep rocking, DevCloud Ninjas!"
Remember to make your script executable with chmod +x vm_info.sh
before running it.
Bonus points if you can add error handling or make the output colorful! π
Drop your scripts in the comments when you're done. Let's see what you've got, Ninjas! And remember, if you get stuck, our community is here to help. Happy scripting! π»βοΈ
#!/bin/bash
echo "Welcome to the system information script!"
Display number of CPU cores
cpu_cores=$(nproc)
echo "Number of CPU cores: $cpu_cores"
Display total amount of RAM
total_ram=$(free -h | awk '/^Mem:/{print $2}')
echo "Total RAM: $total_ram"
Display available disk space
disk_space=$(df -h / | awk 'NR==2 {print $4}')
echo "Available disk space: $disk_space"
List top 3 processes using the most CPU
echo "Top 3 processes using the most CPU:"
ps -eo pid,comm,%cpu --sort=-%cpu | head -n 4
Check if the user running the script is root
if [ "$EUID" -eq 0 ]; then
echo "Warning: You are running this script as root!"
else
echo "You are not running this script as root."
fi
Function to get the current CPU usage
get_cpu_usage() {
top -bn1 | grep "Cpu(s)" | awk '{print "Current CPU usage: " 100 - $8 "%"}'
}
while true; do
Prompt the user
read -p "Do you want to see current CPU usage? (yes/no): " answer
case $answer in
[Yy]* ) # If the user says yes
echo "Showing CPU usage every 5 seconds. Press Ctrl+C to stop."
while true; do
get_cpu_usage # Display CPU usage
sleep 5 # Wait for 5 seconds
done
;;
[Nn]* ) # If the user says no
echo "Goodbye!"
exit # Exit the script
;;
* ) # For any other input
echo "Please answer yes or no."
;;
esac
done