Shell Scripting for System Information: Retrieve Username and Hostname with a Simple Script

Shell Scripting @ Freshers.in

Shell scripting is a powerful tool for automating tasks and retrieving system information in Unix-like operating systems. In this article, we’ll explore how to create a Shell script that prints the current user’s username and the system hostname. Understanding how to gather such system information is a fundamental skill for system administrators, developers, and anyone working in a terminal environment. We’ll provide step-by-step examples and demonstrate the expected output to help you harness the potential of Shell scripting for obtaining crucial system data.

Prerequisites:

Before we begin, ensure that you have the following prerequisites:

  1. A Unix-like operating system (e.g., Linux, macOS).
  2. Basic knowledge of using the command line and a text editor.

Writing the Shell Script:

Let’s create a Shell script to retrieve and display the current user’s username and the system hostname.

#!/bin/bash

# Get the current user's username
username=$(whoami)

# Get the system hostname
hostname=$(hostname)

# Print the information
echo "Current User: $username"
echo "System Hostname: $hostname"

Explanation:

  • We start the script with the shebang #!/bin/bash, indicating that it should be interpreted using the Bash shell.
  • whoami is used to retrieve the current user’s username, and the result is stored in the username variable.
  • hostname is used to obtain the system hostname, and the result is stored in the hostname variable.
  • Finally, we use echo to print both the current user’s username and the system hostname.

Executing the Script:

To execute the script, follow these steps:

  1. Save the Shell script to a file with a .sh extension (e.g., system_info.sh).
  2. Open your terminal or command prompt and navigate to the directory where you saved the script.
  3. Make the script executable by running the command:
    chmod +x system_info.sh
    

Run the script by executing:

./system_info.sh

Output:

Upon running the script, you will see the following output:

Current User: your_username
System Hostname: your_hostname

Replace “your_username” and “your_hostname” with your actual username and system hostname, respectively.

Author: user