When should you use 'su' without a hyphen?

QuestionsQuestions8 SkillsProDec, 17 2025
0112

That's an excellent question! While su - (with the hyphen) is generally recommended for a full environment switch, there are specific situations where using su (without the hyphen) can be appropriate or even desired:

  1. To temporarily execute a single command as another user:
    If you just need to run one or two commands as another user without fully changing your environment or current directory, su <username> can be quicker. You switch, run the command(s), and then exit back to your original session. This is common when you need quick, elevated privileges or access to a file owned by another user in your current working directory.

    • Example: You are in /home/labex/project and need to read a file (student1_report.txt) owned by student1 that's also in this directory, but you don't want to change your current location.
      labex@vm:~/project$ ls -l student1_report.txt
      # (Let's imagine it's owned by student1)
      labex@vm:~/project$ su student1
      Password: student1pass
      student1@vm:/home/labex/project$ cat student1_report.txt
      student1@vm:/home/labex/project$ exit
      labex@vm:~/project$
      Here, student1 can read the file without navigating to their home directory.
  2. Maintaining the current working directory:
    If you're working on files in a shared directory that both users have access to, and you want to continue working in that exact directory as a different user without having to cd back to it, su (without -) is useful. This preserves your current working context.

  3. Specific script requirements:
    Occasionally, a script or application might be designed to run as a different user but rely on environment variables or the current working directory left over from the original user. While rare and generally not best practice, such scenarios could necessitate using su without -.

In summary: Use su without a hyphen when you want to change user identity while largely preserving the original user's environment aspects (like the current working directory and some environment variables that aren't aggressively reloaded) for convenience or specific, temporary tasks.

However, if you want a clean, isolated session that mimics a brand new login for the target user, then su - <username> is almost always the safer and more predictable choice. It ensures the new user's environment is properly set up, reducing the chance of unexpected behavior.

0 Comments

no data
Be the first to share your comment!