Check Mounted File System Usage

ShellBeginner
Practice Now

Introduction

In this challenge, you will write a shell script to check if a specific file system is mounted. Your script will take a file system name (e.g., /dev/vda1) as an argument. Using the df command, it will determine if the file system is currently mounted. If it is, the script will report its usage percentage and the amount of free space available. If it is not mounted, it will display an appropriate error message.

Check Mounted File System Usage

In this challenge, your goal is to create a script that reports the status of a given file system. The script will accept a single command-line argument, which is the name of the file system to check.

Tasks

Your script must perform the following actions:

  1. Accept a single command-line argument representing a file system (e.g., a source listed by df --output=source).
  2. Check if the provided file system is currently mounted on the system.
  3. If the file system is mounted, print a message showing its usage percentage and the available free space in kilobytes (KB).
  4. If the file system is not mounted, or if an incorrect number of arguments is provided, print a clear error message.

Requirements

You must adhere to the following requirements:

  • The script must be named mount.sh and located in the ~/project directory.
  • You must use the df command to gather file system information.
  • Your script should utilize shell arrays and a for loop to process the file system data.
  • The script should handle cases where an incorrect number of arguments is provided.

Example

Here is an example of how your script should work when executed with a valid, mounted file system.

labex:project/ $ bash mount.sh <mounted-filesystem>
Filesystem <mounted-filesystem> is 19% used with 85748032 KB free.

And here is an example for a file system that is not mounted:

labex:project/ $ bash mount.sh /nonexistent
Error: Filesystem /nonexistent is not mounted.

Note: The usage percentage and free space values in the example are for illustration only. Your output will reflect the actual state of the mounted file system you choose in your environment.

Hints

  • You can use df --output=source to get a list of all mounted file system sources.
  • To populate an array with the output of a command, you can use the syntax my_array=($(command)).
  • Remember to check the number of arguments passed to the script using $#.

Summary

In this challenge, you have successfully created a shell script to monitor file system usage. You learned how to process command-line arguments, use the df command with specific output options, and populate arrays with command output. You also practiced iterating through arrays using a for loop to find and display information about a specific file system. This challenge has strengthened your skills in shell scripting, text processing, and system information retrieval.

✨ Check Solution and Practice