Linux get which shell

Different Ways to Check Which Shell You are Using on Linux

A shell is a program through which users can interact with the Operating System. Linux provides commonly 4 types of Shell The Bourne Shell ( /bin/sh or /sbin/sh ), The C shell ( /bin/csh ), The Korn Shell ( /bin/ksh ), The GNU Bourne-Again Shell ( /bin/bash ). This article is about to Check that which shell we are using. Here, we discuss five ways by which we can check which shell we are using.

1) Using echo command: Basically, the echo command is used to print the input string, but it is also used to print the name of the shell which we are using with the help of the command.

2) Using ps command: ps command stands for “Process Status”. It is used to check the currently running status and their PIDs. If the ps command is run generally in the shell then it simply tells the name of the shell.

2. Shell name using ps

The first column tells the PID and the last column tells the type of shell i.e. bash.

3) By viewing /etc/passwd file: This tells the feature of the user just like it’s name, shell, and ID. This command is used with the grep command.

4) Using lsof command: lsof stands for LIST OF OPEN FILES. This command used when we want the list of open files in our system. By using the specific flag it gives a pointer to the shell and tells us about that which shell are we using and that specific flag is -p $$. The command looks like.

As you can see clearly in the 3rd line it tells us about the shell we are using.

5) Using readlink /proc/$$/exe: The readlink is used to print the file name. So with the help of this, we print the location of the current shell using the /proc/$$/exe. Command can be written as

Источник

Как определить и изменить командную оболочку (shell) в Linux

Что такое командная оболочка

Командная оболочка или командный интерпретатор в Linux — это программа, которая в текстовой среде выступает в качестве интерфейса между пользователем и операционной системой. Она интерпретирует вводимые команды с терминала и вызывает необходимые программы.

Когда вы работаете в терминале, именно командная оболочка обрабатывает вводимые вами команды. Более того, оболочки Linux поддерживают написание программ на языке оболочки.

Оболочки Linux

Одна из самых популярных командных оболочек — это оболочка Bash (Bourne Again Shell). Она используется по умолчанию в большинстве дистрибутивов Linux.

Существуют разные оболочки Linux. Можно отметить:

  • bash
  • csh
  • dash
  • fish
  • ksh
  • pdksh
  • rbash
  • sh
  • tcsh
  • zsh

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

Как определить текущую командую оболочку

Есть несколько способов определить оболочку, используемую по умолчанию в вашей системе Linux. Рассмотрим несколько из них, так как в разных системах (и оболочках) какие-то способы могут не сработать.

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

Читайте также:  Система тегов для windows

Способ 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 option. The following command selects the processes whose process ID numbers appear in pid. Use the following command to find out which shell you are in:
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
Читайте также:  Cloud station для windows

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:

  1. ps -p $$ – Display your current shell name reliably.
  2. echo «$SHELL» – Print the shell for the current user but not necessarily the shell that is running at the movement.
  3. echo $0 – Another reliable and simple method to get the current shell interpreter name on Linux or Unix-like systems.
  4. readlink /proc/$$/exe – Another option to get the current shell name reliably on Linux operating systems.
  5. cat /etc/shells – List pathnames of valid login shells currently installed
  6. grep «^$USER» /etc/passwd – Print the default shell name. The default shell runs when you open a terminal window.
  7. 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:

Источник

How to Find Which Shell You Are Using on Linux

Which Shell am I using in Linux? Is that even a question? Of course, it is. There are several shell available for Linux systems. Some of the most popular ones are:

You may wonder this in a few situations.

For example, if you log into a Linux system not known to you, you may wonder which shell is being used by default. If you frequently change shell in Linux, you might wonder which shell you are using at the moment.

Let me show you various Linux commands to find out which shell you are using.

Find out which shell you are using in Linux

Now there is no command that will give you this output with 100% accuracy for all the shells. But these commands should be accurate for most of the shells.

Method 1

You can use the special shell parameter $$. “$$” indicates the process id of the current instance of the shell you are running. This is a read-only parameter and cannot be modified.

If you try to see the process information, it should show you the process name i.e. the shell here.

The output should be like this:

Method 2

You can also use $0. $0 can be the name of the shell or the name of shell script. When it is used inside a shell script, it denotes the name of the script.

But if you use it in a shell without filename, it will show the name of the shell.

The output will simply have the name of the shell:

Method 3

You can also use the pstree command. pstree means process tree and it shows all the running processes as a tree.

If you provide it no argument, it will show all the processes from init or systemd.

However, if you give it a process id, it will show all that process as the root of the tree. In other words, it will show all the processes initiated by that process.

You can use the same $$ bash parameter we saw in method 1.

Method 4

The last method is using the files in proc directory. If you read the article about checking CPU info in Linux, you probably already know that this directory contains the runtime system information about your Linux system.

Читайте также:  Отключить автозамену языка windows 10

You can use the following command to get the shell you are using:

The output should give you the name of the shell.

Bonus Tip: Know the version of the shell

So you learned how to know which shell you are using. What about the version of the shell you are using? You can get the version of the shell simply by adding –version after the name of your running shell.

For example, if you are running zsh, you can use this:

The output will give you the version information:

I hope this quick tutorial helped you in finding out which shell you are running. Don’t forget to check out another simple tip on changing shell in Linux.

By the way, do you use some other way to check which shell you are using? Why not share it with us in the comment section?

Источник

4 Ways to Check Which Shell You are Using on Linux

Out of the box, Linux provides a wide variety of shells. There is bash (Bourne Again shell) shell which ships by default in many Linux distributions. We also have sh (Bourne Shell), tcsh (TC shell), csh (C shell), Zsh (Z shell) and ksh (Korn Shell).

Curious to know which shell you are using on your Linux system? In this guide, we explore different ways that you can use to check which shell you are currently using in Linux.

1) Using echo command

The Linux echo command is a built-in command that is used to print the output of a string which is passed as an argument. Additionally, you can use the echo command to check the shell that you are running commands in. To accomplish this, execute:

The output shows that I am using the bash shell. Additionally, you can simply run the command:

To get the PID of the shell that you are currently in, run:

2) Using ps command

Commonly used for listing running processes, the ps command in its basic format sheds light on the shell that you are using. Simply execute the command:

From the first line of the output, we can clearly see the PID of the shell and the last column prints out the type of shell, in this case — bash.

Alternatively, you can run the command:

You can also use ps -p $$ -o args= which output just the shell name.

3) By viewing /etc/passwd file

The grep command can be used to probe the /etc/passwd file that contains attributes of the users such as username, user ID and group ID.

To display the shell used, invoke the command:

At the very last segment, we get to see the bash used, in this case /bin/bash This also gives you a glimpse of which shell is opened first when you first log in to your system.

4) Using lsof command

Ordinarily, the lsof command, short for list of open files, is used to provide a list of open files on your system. However, when used with the -p $$ flag, it gives a pointer to the shell you are in when you look at the first column of the output.

For example, we can clearly see that we are on the bash shell.

How to check the valid login shells

We have seen various ways that you can employ to check the shell that you are currently in. If you want to know the valid shells on your system, check the /etc/shells file, This file will provide you with the full pathnames of valid login shells in your system. Using the cat command, view the file as shown:

Conclusion

In this guide, we have shared simple but nifty ways that you can use to know which shell you are working on. This is important when writing scripts so that you can know how to start off writing the shebang header. We do hope that this tutorial was beneficial. Send us a shout and don’t forget to share this guide on your social platforms.

Источник

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