DEV Community

kingyou
kingyou

Posted on

Do Something While Someone Logs Into Your Linux System

Have you ever wanted to automatically run a script, display a message, or execute a command when someone logs into your Linux system? Whether you're setting up a welcome message, initializing environment variables, or running system checks, Linux provides several powerful ways to execute commands during the login process.

In this tutorial, I'll walk you through the different methods and best practices for running commands on user login.

Understanding Linux Login Scripts

When a user logs into a Linux system, several configuration files are executed in a specific order. Understanding these files is key to choosing the right place for your commands.

The Main Players

1. /etc/profile - System-wide configuration

  • Executed for all users during login shell
  • Requires root access to modify
  • Perfect for global settings

2. ~/.bash_profile - User-specific login shell

  • Executed when user logs in (SSH, console login)
  • Runs once per login session
  • Ideal for environment setup

3. ~/.bashrc - Interactive shell configuration

  • Executed every time a new terminal/shell is opened
  • Runs for both login and non-login shells
  • Great for aliases and functions

4. ~/.profile - Generic shell configuration

  • Used if .bash_profile doesn't exist
  • Works with various shells (not just bash)
  • Good for portable configurations

Method 1: Using .bash_profile (Recommended)

For most use cases, adding commands to .bash_profile is the best approach. This file executes once when the user logs in.

# Edit your .bash_profile
vim ~/.bash_profile

# Add your command at the end
echo "Welcome back, $USER! System uptime: $(uptime -p)"

# Or run a script
/path/to/your/script.sh
Enter fullscreen mode Exit fullscreen mode

Practical Example: System Info Display

# Add to ~/.bash_profile
echo "=========================================="
echo "Welcome, $USER!"
echo "Today is: $(date +'%A, %B %d, %Y')"
echo "System: $(uname -s) $(uname -r)"
echo "Hostname: $(hostname)"
echo "Load Average: $(uptime | awk -F'load average:' '{print $2}')"
echo "=========================================="
Enter fullscreen mode Exit fullscreen mode

Method 2: Using .bashrc for Every Shell

If you want commands to run every time a new terminal is opened (not just on login):

# Edit .bashrc
vim ~/.bashrc

# Add your commands
alias ll='ls -lah'
export PATH=$PATH:$HOME/bin

# Run a function
greeting() {
    echo "Hello from terminal at $(date +'%H:%M')"
}
greeting
Enter fullscreen mode Exit fullscreen mode

Method 3: Combining .bash_profile and .bashrc

The best practice is to have .bash_profile source .bashrc so your configurations work for both login and non-login shells:

# In ~/.bash_profile
if [ -f ~/.bashrc ]; then
    source ~/.bashrc
fi

# Your login-specific commands here
echo "Login session started"
Enter fullscreen mode Exit fullscreen mode

Method 4: System-Wide Configuration

For commands that should run for ALL users (requires root):

# Edit system-wide profile
sudo vim /etc/profile

# Add at the end
echo "Company Server - Authorized Use Only"
echo "Contact: admin@company.com"
Enter fullscreen mode Exit fullscreen mode

Advanced: Running Background Tasks on Login

For services or monitoring scripts that should run in the background:

# In ~/.bash_profile

# Start a monitoring script in background
if ! pgrep -u $USER monitor.sh > /dev/null; then
    nohup ~/scripts/monitor.sh > /dev/null 2>&1 &
fi
Enter fullscreen mode Exit fullscreen mode

Real-World Use Cases

1. SSH Key Agent Setup

# Auto-start SSH agent on login
if [ -z "$SSH_AUTH_SOCK" ]; then
    eval $(ssh-agent -s)
    ssh-add ~/.ssh/id_rsa 2>/dev/null
fi
Enter fullscreen mode Exit fullscreen mode

2. Docker Environment Check

# Check if Docker is running
if ! docker ps > /dev/null 2>&1; then
    echo "Warning: Docker is not running!"
fi
Enter fullscreen mode Exit fullscreen mode

3. Git Status Summary

# Show git repos status
for repo in ~/projects/*/; do
    if [ -d "$repo/.git" ]; then
        cd "$repo"
        if [ -n "$(git status --porcelain)" ]; then
            echo "Uncommitted changes in: $(basename $repo)"
        fi
    fi
done
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. Keep it fast - Login scripts should execute quickly. Avoid long-running commands.

  2. Use conditionals - Check if a command is necessary before running:

   [ -f ~/important.txt ] && cat ~/important.txt
Enter fullscreen mode Exit fullscreen mode
  1. Redirect output - For background tasks:
   command > /dev/null 2>&1 &
Enter fullscreen mode Exit fullscreen mode
  1. Test in a subshell - Before modifying login scripts:
   bash --login  # Test your changes
Enter fullscreen mode Exit fullscreen mode
  1. Backup first - Always backup configuration files:
   cp ~/.bash_profile ~/.bash_profile.backup
Enter fullscreen mode Exit fullscreen mode

Debugging Login Scripts

If your login script isn't working:

# Enable bash debugging
bash -x ~/.bash_profile

# Check if file is being sourced
echo "Profile loaded" >> ~/login-debug.log

# Verify file permissions
ls -la ~/.bash_profile
Enter fullscreen mode Exit fullscreen mode

Security Considerations

⚠️ Important Security Notes:

  • Never add sensitive credentials directly to these files
  • Be careful with system-wide scripts in /etc/profile
  • Validate user input if your script processes arguments
  • Use absolute paths for commands to avoid PATH hijacking

Conclusion

Automating tasks on user login is a powerful way to enhance your Linux workflow. Whether you're setting up development environments, displaying system information, or running maintenance tasks, understanding login scripts will make you more productive.

Start with simple commands in ~/.bash_profile, test thoroughly, and gradually build more sophisticated automation as needed.

Have you implemented any interesting login scripts? Share your use cases in the comments!


Quick Reference:

  • Login shell: Use ~/.bash_profile
  • Every new terminal: Use ~/.bashrc
  • All users: Use /etc/profile (requires root)
  • Best practice: Source .bashrc from .bash_profile

Happy scripting! 🚀

Top comments (0)