Can 'whoami' be used in scripts?

QuestionsQuestions8 SkillsProYour First Linux LabSep, 20 2025
0102

Yes, the whoami command can be used in scripts! It is particularly useful for determining the current user executing the script, which can help tailor the script's behavior based on user permissions or roles.

Example of Using whoami in a Script

Here’s a simple example of a shell script that uses whoami:

#!/bin/bash

# Get the current user
current_user=$(whoami)

# Check if the user is 'admin'
if [ "$current_user" == "admin" ]; then
    echo "Welcome, Admin! You have full access."
else
    echo "Hello, $current_user! You have limited access."
fi

Explanation

  1. Shebang (#!/bin/bash): This line indicates that the script should be run in the Bash shell.
  2. Variable Assignment: current_user=$(whoami) captures the output of whoami and stores it in the variable current_user.
  3. Conditional Statement: The script checks if the current user is "admin" and provides different messages based on the user's identity.

Benefits of Using whoami in Scripts

  • Dynamic Behavior: Scripts can adapt their functionality based on the user running them.
  • Security: You can restrict certain actions to specific users, enhancing security.

Feel free to experiment with this in your own scripts, and let me know if you have any further questions or need additional examples!

0 Comments

no data
Be the first to share your comment!