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.

Читайте также:  Установка зависимостей linux astra

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.

Читайте также:  How to change file permissions in linux

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).

Источник

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

Хотелось бы рассказать в своей статье «Получить имя текущего пользователя в Unix/Linux» как можно получить имя текущего пользователя в Unix/Linux. Я, использовал только несколько, но нашел еще несколько о которых и не знал.

Самый простой способ получить текущего пользователя — это выполнить следующую команду:

Так же, можно воспользоваться переменным окружением и вывести следующий параметр:

Читайте также:  Send file linux command

Так же, можно получить пользователя по ID:

Так же, можно получить пользователя по PID:

Можно использовать утилиту «w» и она покажет пользователя:

Вот еще один пример хорошей утилиты:

Вот и все, тема «Получить имя текущего пользователя в Unix/Linux» завершена.

Добавить комментарий Отменить ответ

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.

Рубрики

  • Arch Linux (167)
  • Commands (36)
  • Debian’s (635)
    • Administration tools Ubuntu (37)
    • Backups Debian’s (7)
    • Database в Ubuntu (58)
    • Games (игры) (1)
    • Monitoring в Debian и Ubuntu (49)
    • Virtualization в Ubuntu / Debian/ Linux Mint (41)
      • Docker (22)
      • Kubernetes (6)
      • KVM (4)
      • OpenVZ (3)
      • Vagrant (5)
      • VirtualBox (6)
      • ArgoCD (1)
      • Concourse (1)
      • Gitlab (1)
      • Jenkinks (4)
      • Spinnaker (1)
      • Apache (32)
      • Cherokee (1)
      • FTP-services (5)
      • Lighttpd (1)
      • Nginx (26)
      • PHP (27)
      • Proxy для Debian’s (2)
      • Tomcat (4)
      • Панели управления в Ubuntu/Debian/Mint (24)
      • Установка и настройка почты на Ubuntu/Debian (12)
      • Хранилища (clouds) (2)
      • Administration tools freeBSD (19)
      • Database во FreeBSD (52)
      • Monitoring во freeBSD (37)
      • Virtualization во FreeBSD (22)
      • VoIP (1)
      • Установка Web сервисов (91)
      • Установка и настройка почты (6)
      • Установка из ports (пакетов) (19)
      • Установка из sorce code (исходников) (23)
      • Непрерывная интеграция (CI) (27)
      • Database в MacOS (36)
      • Monitoring в Mac OS (31)
      • Security (безопасность) (12)
      • Virtualization в Mac OS (30)
        • Docker (19)
        • Kubernetes (6)
        • Vagrant (5)
        • VirtualBox (5)
        • ArgoCD (1)
        • CircleCI (1)
        • Concourse (1)
        • Gitlab (1)
        • Jenkinks (4)
        • Spinnaker (1)
        • Administration tools CentOS (49)
        • Backups RPM’s (4)
        • Database в CentOS (68)
        • Monitoring в CentOS (67)
        • Virtualization в CentOS/ Red Hat/ Fedora (42)
          • Docker (23)
          • Kubernetes (6)
          • KVM (5)
          • OpenVZ (2)
          • Vagrant (5)
          • VirtualBox (6)
          • VMWare (3)
          • ArgoCD (1)
          • Concourse (1)
          • Gitlab (1)
          • Jenkinks (4)
          • Spinnaker (1)
          • Apache (35)
          • Cherokee (1)
          • DNS (3)
          • FTP (10)
          • Nginx (33)
          • PHP (34)
          • Proxy для RedHat’s (2)
          • Tomcat (2)
          • Voice (2)
          • Панели управления в CentOS/Red Hat/Fedora (27)
          • Прокси сервер на CentOS/RHEL/Fedora (4)
          • Установка и настройка почты на CentOS/RHEL/Fedora (14)
          • Хранилища (clouds) (1)

          соц сети

          Unix-Linux- в примерах

          Unix-Linux- в примерах

          Unix-Linux- в примерах

          Архив новостей

          Свежие записи

          Свежие комментарии

          • Глеб к записи Установка Adobe Flash Player в Debian/Ubuntu/Mint
          • Максим к записи Заблокировать User Agents используя Nginx
          • Денис к записи Как включить EPEL репозиторий на CentOS
          • Гость к записи Закомментировать/Раскомментировать строки vi/vim в Unix/Linux
          • Sergey к записи Установка и настройка OpenVPN сервера на Debian/Ubuntu/Linux Mint

          Источник

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