Получить имя текущего пользователя linux

How do I get the current user’s username in Bash?

It seems none of the methods proposed so far work without relying on $USER or invoking a separate process. Is there no bash builtin to get the username without invoking a separate process?

When you’ve heard a command but aren’t sure how to use it, checking man whoami is usually a good first stop to check for documentation.

14 Answers 14

On the command line, enter

Just a quick note that $USER and whoami return different values if your running a command through ssh as another user. whoami returns the OS user and $USER returns the ssh user.

In some cases, $USER is not set at all. Worse, it is just an environment variable, so it can be overridden by the user: USER=thisisnotmyname bash -c ‘echo $USER’ # prints thisisnotmyname

@SethMMorton I realise I made the issue sound worse than it usually is. To answer the question, though, using whoami (as you suggested) eliminates the problem altogether, assuming overridden environment variables is a potential issue in your context.

«current username» is slightly ambiguous. What do you want to get when running under sudo? «echo $USER» produces the name I logged in as whether run under sudo or not, while «whoami» returns «root» when run under sudo and my actual login name otherwise. Scripts that need to be run as sudo are more likely to be in that minority of scripts that have need of your login name rather than «root».

An alternative to whoami is id -u -n .

id -u will return the user id (e.g. 0 for root).

Unless I’m mistaken this would be the way to go if portability is a concern as the id command and -u and -n flags are a part of posix

This really should be the accepted answer. «$» and whoami both depend on how you log in. Specifically, login shells and sudo will set $USER, and whoami looks at the user attached to stdin. However, if you are running a batch job from cron, or you are running a startup script as a different user than root, then these will either output the wrong user (root) or nothing at all. This answer will return the correct value regardless by looking at process’s user ID.

if you tried the command before adding untrue comments, you would see that the -n argument prints the username, just like the original question asked. see the following: id -u -n prints brett — even on darwin.

A great alternative when checking on live container instances with very few command line apps installed. whoami isn’t installed on many of the lite images out there.

Use the standard Unix/Linux/BSD/MacOS command logname to retrieve the logged in user. This ignores the environment as well as sudo, as these are unreliable reporters. It will always print the logged in user’s name and then exit. This command has been around since about 1981.

My-Mac:~ devin$ logname devin My-Mac:~ devin$ sudo logname Password: devin My-Mac:~ devin$ sudo su - My-Mac:~ root# logname devin My-Mac:~ root# echo $USER root 

This was particularly helpful to me over whoami or $USER as I am using sudo to execute as another user, but want the original user not the sudo user.

Читайте также:  Медиа нав линукс альтернативная прошивка

BTW this is the best answer, not only for me personally but also to the purpose of the OP’s question.

A hack the I’ve used on Solaris 9 and Linux and which works fine for both of them:

This snippet prints the name of the user with the current EUID.

NOTE: you need Bash as the interpreter here.

On Solaris you have problems with methods, described above:

  • id does not accept the -u and -n parameters (so you will have to parse the output)
  • whoami does not exist (by default)
  • who am I prints owner of current terminal (ignores EUID)
  • $USER variable is set correctly only after reading profile files (for example, /etc/profile )

Why do you need bash as the interpreter? Nothing in the command line shown seems to be specific to any shell. In fact, why even include the pipe through awk? As far as I can tell, your ps command is everything required to display the owner of the current shell’s pid.

For us as humans to disregard the superfluous information is natural. The awk portion isolates the desired data— for variables or in general the computer that can’t make on the fly assumptions just yet at this rudimentary level.

On Solaris, use command -p id (from a POSIX shell) or /usr/xpg4/bin/id . More generally, on Solaris, you’d want to modify your environment to put yourself in a POSIX environment (with something like PATH= getconf PATH` and be sure to run /usr/xpg4/bin/sh ) to avoid being stuck with commands from the 70s/80s.

  1. id prints the user id along with the groups. Format: uid=usernumber(username) .
  2. whoami gives the current user name

$whoami isn’t available as a variable in bash. You need to do either $(whoami), or `whoami` to actually execute the whoami command!

When root (sudo) permissions are required, which is usually 90%+ when using scripts, the methods in previous answers always give you root as the answer.

To get the current «logged in» user is just as simple, but it requires accessing different variables: $SUDO_UID and $SUDO_USER .

echo $SUDO_UID echo $SUDO_USER 
myuid=$SUDO_UID myuname=$SUDO_USER 

In Solaris OS I used this command:

$ who am i # Remember to use it with space. 

On Linux- Someone already answered this in comments.

Those 2 commands display 2 different informations. Just log as root, use «su — xxx», and see for yourself.

. gets you the regular user (if non-sudo) → or ← the regular user behind the current sudo call.

How could i do it in nested quotes? e.g. my_var=»$(‘/some/path/to/$/more/path’ ‘and/something/else’)»

The current user’s username can be gotten in pure Bash with the $ parameter expansion (introduced in Bash 4.4):

The : built-in (synonym of true ) is used instead of a temporary variable by setting the last argument, which is stored in $_ . We then expand it ( \u ) as if it were a prompt string with the P operator.

This is better than using $USER , as $USER is just a regular environmental variable; it can be modified, unset, etc. Even if it isn’t intentionally tampered with, a common case where it’s still incorrect is when the user is switched without starting a login shell ( su ‘s default).

Источник

How can I find out my user name?

How do I know my username? I’ve installed Ubuntu, but I don’t know my username, only my password. I can’t access my laptop and it can’t be opened.

Читайте также:  Linux mint xrdp настройка

The login screen shows possible accounts and you only have to click (or even not have to click since you were presumably the last to log in) and type your password.

@Jayharte — did any of these answers work for you? If so, please accept one as the answer. Thank you.

9 Answers 9

Open a Terminal and type whoami

This will work on every Unix/Linux System.

@rajlego If run from recovery mode, whoami would just output root . However, in recovery mode, ls /home could be used to view the names of the system’s normally configured human users. If there’s just one such user, this output is their username; and even if there are more, it should make it pretty easy to figure out the username.

Agree with @Boris. As he mentioned in the answer, he could not login, how could he launch whoami ? It’s strange to have this answer got many vote-ups.

@TungTran — Upvotes are from googlers (like me) who came here looking for the answer to the question in the title. Some of us just need a reminder of the command that prints out the current username. But, reading the actual question, this answer is pretty useless to the asker.

This will print the value of USER environment variable to the console.

To the original asker, this is as useless as the whoami command, but in all honesty, this is perfect for those «run a blah username_here » commands where username_here part can be replaced with $USER and the whole command made more universal. Thanks.

@Ali Dehghani, $USER is an environment variable that can be changed to anything. whoami actually checks which is the currently logged in user

Most simple way to find out your username is probably to press ctr+alt+t — this opens terminal and than you will see something like:

And that answers your question.

If you installed ubuntu, then you filled in your username, does this help jog our memory?

E.g. here where yann is the user name

enter image description here

You should boot up your Ubuntu in recovery mode. Follow the steps below:

  • Switch on your computer. Wait until the BIOS has finished loading, or has almost finished. (During this time you will probably see a logo of your computer manufacturer.) Quickly press and hold the Shift key, which will bring up the GNU GRUB menu. (If you see the Ubuntu logo, you’ve missed the point where you can enter the GRUB menu.) **
  • Select the line which starts with «Advanced options«. *
  • Select the line ending with «(recovery mode)«, probably the second line, something like: Ubuntu GNU/Linux, with Linux 3.8.0-26-generic (recovery mode)
  • Press Return and your machine will begin the boot process.
  • After a few moments, your workstation should display a menu with a number of options. One of the options (you may need to scroll down to the bottom of the list) will be «Drop to root shell prompt«. Press Return with this option highlighted.

Eventually, you could use this command to list all usernames:

I suppose you will be able to recognize your username in the list.

This will work if the user hasn’t set their root password ever. However, if someone has set it already, they can always just use a live usb or any other OS to look at the home directory(hopefully unencrypted.)

Читайте также:  Как установить обновления на линуксе

Yes, if he remembers his root password, it’s even easier. Anyway, as he said, he’s installed the Ubuntu and doesn’t know his username. I suppose he didn’t set root password.

Normally when you start your computer, you don’t have to know your username to log on, because it appears automatically in a list. And if it’s the only user account, it’s the only name listed. It should look like this:

enter image description here

If there is more than one user account, click on the name you want to use. For just one user, all you have to do is type in your password.

If your login screen does not look like that, or logging in does not work, or the problem is that booting fails before you get to the login screen, please let us know, and provide as many details as possible.

Источник

Команда Linux для отображения текущего имени пользователя

Команда Linux для отображения текущего имени пользователя

З нание текущего имени для входа важно для определения личности пользователя, который в данный момент вошел в систему, особенно если несколько человек используют одну систему Linux. Для этого существуют различные команды, с помощью которых вы можете найти текущего активного пользователя в Linux Mint. Мы обсудим их в этой статье.

Команды Linux для отображения текущего имени пользователя

По умолчанию дистрибутив Linux имеет запрос имени пользователя в терминале, но если пользователь изменил свое имя, попробуйте выполнить следующие команды, чтобы найти текущее имя для входа. Все, что нам нужно, это открыть терминал и отобразить текущее имя пользователя с помощью следующих команд:

1. Команда who

Команда who отобразит текущее имя пользователя с датой и временем. Он считывает информацию из расположения файла по умолчанию.

Вы также можете -a флаг с командой Who, чтобы получить информацию о текущем вошедшем в систему пользователе:

2. Команда whoami

В отличие от Who, команда whoami будет отображаться прямой ответ только для имени пользователя, поэтому, если вы хотите проверить только имя пользователя, выполните:

3. Команда $USER

Другой способ получить только имя для входа, как в команде whoami, выполнить команду $USER:

4. Команда w

Команда w предоставляет дополнительную информацию о текущем активном пользователе в вашей системе:

Здесь TTY — тип терминала, в который они вошли, FROM — удаленный хост, LOGIN@ — время входа пользователя в систему, JCPU — совместное время ЦП, используемое всеми процессами, PCPU — время ЦП текущего процесса и WHAT — текущий процесс

5. Команда ID

Команда id отображает информацию о пользователе и группах, связанных с конкретным пользователем:

6. Команда logname

Команда logname печатает одно слово, только имя текущего активного пользователя:

7. Команда last

Команда last выводит список пользователей, которые последними вошли в вашу систему:

8. Команда lslogins

Команда lslogins отображает список пользователей, вошедших в систему, с их последним временем входа в систему и их именами, здесь флаг -u отображает только информацию о пользователе:

Выводы

Как и в Linux, в одну и ту же систему могут входить разные пользователи, и в этом случае можно отслеживать их действия. Вы можете найти текущее имя для входа с помощью различных команд в терминале. В этой статье мы научились находить имя пользователя с помощью команд who, whoami, what, w и lslogins.

Попробуйте каждую команду и проверьте, какая из них лучше всего подходит для вас.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

Оцените статью
Adblock
detector