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:
- A Unix-like operating system (e.g., Linux, macOS).
- 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 theusername
variable.hostname
is used to obtain the system hostname, and the result is stored in thehostname
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:
- Save the Shell script to a file with a .sh extension (e.g.,
system_info.sh
). - Open your terminal or command prompt and navigate to the directory where you saved the script.
- 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.