- Linux / Unix Shell Script: Get Current User Name
- Syntax
- Shell script example
- A note about $EUID
- How to determine the current user account in Linux
- Summing up
- What is Linux Shell
- Contents
- What Is a Shell?
- Shell Prompt
- How do I find out my current shell name?
- Command Line Interface (CLI)
- Basic Command Line Editing
- Executing A Command
- Command And File Completion
- Как определить и изменить командную оболочку (shell) в Linux
- Что такое командная оболочка
- Оболочки Linux
- Как определить текущую командую оболочку
- Способ 1
- Способ 2
- Способ 3
- Как посмотреть список оболочек, доступных в системе
- Как временно переключиться на другую оболочку
- Как изменить оболочку
- Заключение
- How do I find out what shell I am using on Linux/Unix?
- How can I find out what shell I am using?
- How do I check which shell am I using?
- How do I check how many shells are installed on my Linux box?
- Okay, so when I open the Terminal app, which shell is opened by default?
- How to check which shell am I using:
- Conclusion
Linux / Unix Shell Script: Get Current User Name
I am working on a shell script. I need to find out the current user name. How do I find out the current user name under Bash or Ksh shell running on Linux or Unix like operating systems? How do I determine the current user account in Linux?
You can use the variables $USER, or $USERNAME which are not Bash builtins. These are, however, set as environmental variables in one of the Bash startup files. You can use the id command to get the same information.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Bash/ksh |
Est. reading time | 1m |
a] $USER – Current user name.
b] $USERNAME – Current user name.
c] id command – Print current user name.
d] whoami command – Show current user name.
Syntax
To get the current user name, type:
Get the current user name and store to a shell variable called $u:
The syntax for id command is:
To print numeric UID, run:
The following script reads user name and store to a variable called _user _uid:
Shell script example
Make sure only root user can run the following script:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
A note about $EUID
This variable EUID is readonly. It expands to the effective user ID of the current user, initialized at shell startup. You can use $EUID to find out if user is root or not with the following syntax:
How to determine the current user account in Linux
We can use the who command as follows to print the current user account:
who
whoami
OR use the id command:
id -u -n
Summing up
We explained how you could find and get the current user’s username in a Bash script and shell prompt using various command-line options. See bash man page for more information by typing the following commands:
man bash
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
What is Linux Shell
Computers understand the language of zeros and ones known as binary language. In the early days of computing, instructions were provided using binary language, which is difficult for all of us to read and write. Therefore, in an operating system there is a special program called the shell. The shell accepts human readable commands and translates them into something the kernel can read and process.
Contents
What Is a Shell?
- The shell is a user program or it is an environment provided for user interaction.
- It is a command language interpreter that executes commands read from the standard input device such as keyboard or from a file.
- The shell gets started when you log in or open a console (terminal).
- Quick and dirty way to execute utilities.
- The shell is not part of system kernel, but uses the system kernel to execute programs, create files etc.
- Several shells are available for Linux including:
- BASH ( Bourne-Again SHell ) — Most common shell in Linux. It’s Open Source.
- CSH (C SHell) — The C shell’s syntax and usage are very similar to the C programming language.
- KSH (Korn SHell) — Created by David Korn at AT & T Bell Labs. The Korn Shell also was the base for the POSIX Shell standard specifications.
- TCSH — It is an enhanced but completely compatible version of the Berkeley UNIXC shell (CSH).
Please note that each shell does the same job, but each understands different command syntax and provides different built-in functions. Under MS-DOS, the shell name is COMMAND.COM which is also used for the same purpose, but it is by far not as powerful as our Linux Shells are!
Shell Prompt
There are various ways to get shell access:
- Terminal — Linux desktop provide a GUI based login system. Once logged in you can gain access to a shell by running X Terminal (XTerm), Gnome Terminal (GTerm), or KDE Terminal (KTerm) application.
- Connect via secure shell (SSH) — You will get a shell prompt as soon as you log in into remote server or workstation.
- Use the console — A few Linux system also provides a text-based login system. Generally you get a shell prompt as soon as you log in to the system.
How do I find out my current shell name?
To find all of the available shells in your system, type the following command:
In case the /etc/shells file has more than one shell listed under it, then it means that more than one shell is supported by your platform.
Command Line Interface (CLI)
The shell provides an interface to Linux where you can type or enter commands using the keyboard. It is known as the command line interface (CLI). To find out your current shell type following command [1] .:
The following sample output indicate that I am using bash shell:
Basic Command Line Editing
You can use the following key combinations to edit and recall commands:
- CTRL + L : Clear the screen.
- CTRL + W : Delete the word starting at cursor.
- CTRL + U : Clear the line i.e. Delete all words from command line.
- Up and Down arrow keys : Recall commands (see command history).
- Tab : Auto-complete files, directory, command names and much more.
- CTRL + R : Search through previously used commands (see command history)
- CTRL + C : Cancel currently running commands.
- CTRL + T : Swap the last two characters before the cursor.
- ESC + T : Swap the last two words before the cursor.
- CTRL + H : Delete the letter starting at cursor.
Executing A Command
Type your command, and press enter key. Try this the date command which will display current date and time:
Command And File Completion
The Bash shell will auto complete file and command names, when possible and/or when you tell them to. For example, if you type sle and pressing Tab key will make the shell automatically complete your command name. Another example, if you type ls /e and pressing Tab key will make the shell automatically complete your word to /etc as it sees that /etc/ is a directory which starts with /e.
Источник
Как определить и изменить командную оболочку (shell) в Linux
Что такое командная оболочка
Командная оболочка или командный интерпретатор в Linux — это программа, которая в текстовой среде выступает в качестве интерфейса между пользователем и операционной системой. Она интерпретирует вводимые команды с терминала и вызывает необходимые программы.
Когда вы работаете в терминале, именно командная оболочка обрабатывает вводимые вами команды. Более того, оболочки Linux поддерживают написание программ на языке оболочки.
Оболочки Linux
Одна из самых популярных командных оболочек — это оболочка Bash (Bourne Again Shell). Она используется по умолчанию в большинстве дистрибутивов Linux.
Существуют разные оболочки Linux. Можно отметить:
- bash
- csh
- dash
- fish
- ksh
- pdksh
- rbash
- sh
- tcsh
- zsh
Оболочки могут очень сильно отличаться друг от друга. Они отличаются функциональностью, синтаксисом команд, строкой приветствия, дружелюбностью к пользователю и другими параметрами и возможностями.
Как определить текущую командую оболочку
Есть несколько способов определить оболочку, используемую по умолчанию в вашей системе Linux. Рассмотрим несколько из них, так как в разных системах (и оболочках) какие-то способы могут не сработать.
Также нужно знать, что у разных пользователей системы могут использоваться разные оболочки.
Способ 1
Переменная окружения SHELL хранит путь до исполняемого файла оболочки. Выполним команду:
Из вывода команды, мы видим, что используется оболочка bash.
Способ 2
Также можно воспользоваться командой echo $0 . Данная команда выведет на экран имя текущего работающего процесса, внутри которого она выполнена. Так как мы выполняем команду внутри оболочки, то будет выведено имя оболочки.
Способ 3
Определим, работающий процесс оболочки командой ps.
Как посмотреть список оболочек, доступных в системе
Список оболочек, которые в данный момент установлены и доступны в системе Linux, хранится в файле /etc/shells
Выведем содержимое файла /etc/shells , для этого выполняем команду:
Как временно переключиться на другую оболочку
Чтобы временно переключиться на другую оболочку, достаточно выполнить в терминале команду, соответствующую ее имени. После этого вы переключитесь на новую оболочку.
Например, переключимся на оболочку sh. Выполняем команду:
Как изменить оболочку
Для изменения командной оболочки на постоянной основе служит команда chsh (от слов change shell).
Чтобы изменить оболочку текущего пользователя нужно выполнить команду:
В качестве параметра путь_новой_оболочки необходимо указать путь до исполняемого файла оболочки, который вы можете найти в файле /etc/shells (см. выше).
Например, изменим оболочку на sh. Для этого выполняем команду (при выполнении команды нужно будет ввести пароль):
После этого нужно выйти и снова войти в систему.
Чтобы изменить оболочку, используемую по умолчанию, для другого пользователя, то команде chsh необходимо указать имя этого пользователя:
Заключение
Мы рассмотрели, как определить текущую оболочку Linux, как просмотреть список доступных оболочек, а также как изменить оболочку, используемую по умолчанию.
Чтобы получить информацию о какой-либо оболочке (доступной в системе) можно воспользоваться Man-страницами. Например:
Дополнительные оболочки можно устанавливать средствами системы (из репозиториев). Например, для установки оболочки fish в Ubuntu Linux, выполните команду
Источник
How do I find out what shell I am using on Linux/Unix?
B oth Linux and Unix provides various shell out of the box. One can find bash (Bourne Again shell), ksh (Korn shell), csh (C shell)/tcsh (TC shell), sh (Bourne shell) and more installed by default. However, how do you check which shell am I using? What is the best way to find out what shell I am using on Linux? The echo $SHELL is not so reliable. This page explains how to find out which shell I am using at a Linux, MacOS, FreeBSD, or Unix-like systems.
How can I find out what shell I am using?
The following echo command or printf command should work:
echo «$SHELL»
OR
printf «My current shell — %s\n» «$SHELL»
Please note that $SHELL is the shell for the current user but not necessarily the shell that is running at the moment. Try the following examples
How do I check which shell am I using?
Here is another old good Unix trick. Use the ps command with -p
ps -p $$
Sample outputs:
So what is a $ argument passed to the -p option? Remember $ returns the PID (process identification number) of the current process, and the current process is your shell. So running a ps on that number displays a process status listing of your shell. In that listing, you will find the name of your shell (look for CMD column).
ps -p $$
Sample outputs:
From my Linux box:
ps -p $$
Sample outputs:
You can store your shell name in a variable as follows :
MYSHELL=`ps -hp $$|awk ‘
Please note those are backquotes, not apostrophes. Or better try out the following if you have a bash shell:
MYSHELL=$(ps -hp $$|awk ‘
Another option is as follows:
echo $0
OR
printf «%s\n» $0
Sample outputs from the above commands:
Fig.01: Linux check which shell am I using
How do I check how many shells are installed on my Linux box?
The /etc/shells is a text file which contains the full pathnames of valid login shells. Type the following [nixmd name=”cat”] to see list how many shells are installed on your Linux or Unix box:
cat /etc/shells
Use /etc/shells file to check how many shells are installed on your system
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Okay, so when I open the Terminal app, which shell is opened by default?
Your default shell is defined in /etc/passwd file. So try the following grep command:
How to check which shell am I using:
Use the following Linux or Unix commands:
- ps -p $$ – Display your current shell name reliably.
- echo «$SHELL» – Print the shell for the current user but not necessarily the shell that is running at the movement.
- echo $0 – Another reliable and simple method to get the current shell interpreter name on Linux or Unix-like systems.
- readlink /proc/$$/exe – Another option to get the current shell name reliably on Linux operating systems.
- cat /etc/shells – List pathnames of valid login shells currently installed
- grep «^$USER» /etc/passwd – Print the default shell name. The default shell runs when you open a terminal window.
- chsh -s /bin/ksh – Change the shell used from /bin/bash (default) to /bin/ksh for your account
Conclusion
Sometimes things are not easy as they seem, and this page is the perfect example of it. I hope you found the suggestion useful when it comes to checking your current running shell. Bash users can display shell version by typing the following command:
$ bash —version
Here is what I got from my Ubuntu Linux 20.04 LTS desktop:
Источник