su is a command used to switch the current user to another user. The - option is used to specify that you want to switch to the target user's environment.
For example, if you run su bilal, you will be prompted for the password of the bilal user, and then you will be logged in as bilal. However, your environment (e.g., current working directory, environment variables) will not be changed.
On the other hand, if you run su - bilal, you will again be prompted for the password of the bilal user, but this time your environment will be changed to match that of the bilal user. This includes changing the current working directory to the bilal user's home directory, as well as setting all of the bilal user's environment variables.
In general, it is recommended to use su - when switching to another user, as this ensures that your environment is correctly set up for the target user.
if you want to switch to a different user (must have a password for that user)
First, create a user name bilal, and set a password for him
sudo useradd -m bilal sudo passwd bilal
let's switch to bilal , it will prompt you for the bilal password you set in the previous step, Notice the pwd will still be the /home/usama and user bilal doesn't have permission for ls in the usama directory
Let's switch to bilal with su - bilal way, this time home directory will also change to the user bilal, you got the point.
Notice that this time not only does the directory get changed and also you can list bashrc, and profile files of user bilal. it means it got loaded
su - bilal
let's edit .profile file and define the environment variable and echo something
echo "User Bilal is log in to in this Ubuntu 22.04" A=helloworld
exit from vim file and user bilal and again su -bilal
su - bilal
Notice above the difference between
when you switch to su - bilal
profile file loaded and it has echo the text and our env var A is also printing
but in the case of su bilal
it is neither printing var A nor echo text we define in .profile file.
su - (means root if you will not anything after - )
sudo su (for switching to root user if you have not set a password for root and the current user should have sudo privileges )
su (it will also switch to user root without env, profile, etc)