0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use $USER in Bash: Simple Guide

In bash, $USER is an environment variable that holds the current logged-in username. You can use it in scripts or commands by prefixing it with a dollar sign, like echo $USER, to display the username.
📐

Syntax

The $USER variable is used by prefixing it with a dollar sign to access its value. It contains the username of the current user logged into the system.

  • $USER: The variable holding the username.
  • Use it in commands or scripts by writing $USER.
bash
echo $USER
Output
your_username
💻

Example

This example shows how to print a greeting message using the $USER variable in bash.

bash
#!/bin/bash

echo "Hello, $USER! Welcome to your bash session."
Output
Hello, your_username! Welcome to your bash session.
⚠️

Common Pitfalls

One common mistake is forgetting the dollar sign and writing USER instead of $USER, which will not print the username but the literal string "USER". Another pitfall is using single quotes around $USER, which prevents variable expansion.

Correct usage requires double quotes or no quotes for the variable to expand.

bash
echo USER
# Wrong: prints USER literally

echo '$USER'
# Wrong: prints $USER literally

echo "$USER"
# Correct: prints the username
Output
USER $USER your_username
📊

Quick Reference

Remember these tips when using $USER in bash:

  • Always prefix with $ to access the variable.
  • Use double quotes if you want to include it in strings.
  • $USER is set by the system and reflects the current logged-in user.

Key Takeaways

Use $USER to get the current logged-in username in bash.
Always prefix the variable name with $ to access its value.
Use double quotes around $USER in strings to allow variable expansion.
Avoid single quotes around $USER as it prevents expansion.
$USER is set automatically by the system environment.