Как изменить shell на bash

Как сменить командную оболочку Linux. Как определить и изменить Shell.
Как изменить оболочку Shell в Linux

Оглавление

  • Что такое командная оболочка
  • Оболочки Linux
  • Как определить текущую командую оболочку
    • Способ 1
    • Способ 2
    • Способ 3
  • Как посмотреть список оболочек, доступных в системе
  • Как временно переключиться на другую оболочку
  • Как изменить оболочку
  • Заключение

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

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

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

Оболочки Linux

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

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

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

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

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

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

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

Способ 1

Переменная окружения SHELL хранит путь до исполняемого файла оболочки. Выполним команду:

echo $SHELL
/bin/bash

Из вывода команды, мы видим, что используется оболочка bash.

Способ 2

Также можно воспользоваться командой echo $0. Данная команда выведет на экран имя текущего работающего процесса, внутри которого она выполнена. Так как мы выполняем команду внутри оболочки, то будет выведено имя оболочки.

echo $0
bash

Способ 3

Определим, работающий процесс оболочки командой ps.

ps -p $$
PID TTY TIME CMD
10792 pts/3 00:00:00 bash

Определить текущую оболочку Shell в Linux

Как посмотреть список оболочек, доступных в системе

Список оболочек, которые в данный момент установлены и доступны в системе Linux, хранится в файле /etc/shells

Выведем содержимое файла /etc/shells, для этого выполняем команду:

cat /etc/shells
# /etc/shells: valid login shells
/bin/sh
/bin/bash
/bin/rbash
/bin/dash

Список командных оболочек Linux

Как временно переключиться на другую оболочку

Чтобы временно переключиться на другую оболочку, достаточно выполнить в терминале команду, соответствующую ее имени. После этого вы переключитесь на новую оболочку.

Например, переключимся на оболочку sh. Выполняем команду:

sh

Переключиться на другую оболочку в Linux

Как изменить оболочку

Для изменения командной оболочки на постоянной основе служит команда chsh (от слов change shell).

Чтобы изменить оболочку текущего пользователя нужно выполнить команду:

chsh -s путь_новой_оболочки

В качестве параметра путь_новой_оболочки необходимо указать путь до исполняемого файла оболочки, который вы можете найти в файле /etc/shells (см. выше).

Например, изменим оболочку на sh. Для этого выполняем команду (при выполнении команды нужно будет ввести пароль):

chsh -s /bin/sh

После этого нужно выйти и снова войти в систему.

Чтобы изменить оболочку, используемую по умолчанию, для другого пользователя, то команде chsh необходимо указать имя этого пользователя:

chsh -s /bin/sh yuriy

Заключение

Мы рассмотрели, как определить текущую оболочку Linux, как просмотреть список доступных оболочек, а также как изменить оболочку, используемую по умолчанию.

Чтобы получить информацию о какой-либо оболочке (доступной в системе) можно воспользоваться Man-страницами. Например:

man rbash

Дополнительные оболочки можно устанавливать средствами системы (из репозиториев). Например, для установки оболочки fish в Ubuntu Linux, выполните команду

sudo apt install fish

In most Linux systems, the default shell is bash but we can change that to any other shell-like zsh, fish, sh, and any other. In this article, we are going to show how to change that default shell to any other shell in Linux systems. To change the user’s shell, first, let’s find the current shell. There are many ways by which we can change the shell of any user on a Linux system. We are going to see three methods of changing the user’s shell.

Find your current shell name

In Linux systems, there is one file which is /etc/passwd. The /etc/passwd file stores essential information of user accounts, which is required during login. By using this file we can identify the current user login shell.

We are going to see the current user information in the /etc/file using the following command:

grep `whoami` /etc/passwd

In the above image we can see that the user nishant (current user) has home directory /home/nishant and the shell is /bin/sh

List your shells in Linux

Now to change the shell, first, we need to see which shells are installed on the system. We can check installed shells using the following command :

cat /etc/shells

This will show all shells as follows:

Before moving further, first understand who can change the user shell

  • Users can change shell to any other shell listed in /etc/shells/.
  • The root account can be used to change any other user login shell.
  • If an account has a restricted login shell, then only the root can change that user’s shell.

Changing default sh shell to bash

Using usermod command

usermod is a command that modifies the system account files. usemod can change the shell of Users by modifying file /etc/passwd. usermod command provides the -s or –shell option to change the user’s login shell.

In this example, we are going to change the shell of a user named nishant. We are going to change the shell from /bin/sh to /bin/bash of user nishant using usermod command.

sudo usermod --shell /bin/bash nishant

With usermod command mention shell and username after –shell option.

Now you can see the shell use changed. In the above commands, replace nishant with the user name whose shell has to change.

Using chsh Utility

chsh is the utility to change a user’s login shell. chsh provides the -s option to change the user’s shell. This method also modifies the file /etc/passwd. Use the following command to change shells using chsh:

chsh -s /bin/bash nishant

Change User Shell to /etc/passwd File

 As we see in the above two methods, the usermod command and chsh utility modify the /etc/passwd file and change the user shell. We can do that manually also by editing the /etc/passwd file. Just change the shell after the username and home directory in the /etc/passwd file and save the file.

nano /etc/passwd

In most Linux systems, the default shell is bash but we can change that to any other shell-like zsh, fish, sh, and any other. In this article, we are going to show how to change that default shell to any other shell in Linux systems. To change the user’s shell, first, let’s find the current shell. There are many ways by which we can change the shell of any user on a Linux system. We are going to see three methods of changing the user’s shell.

Find your current shell name

In Linux systems, there is one file which is /etc/passwd. The /etc/passwd file stores essential information of user accounts, which is required during login. By using this file we can identify the current user login shell.

We are going to see the current user information in the /etc/file using the following command:

grep `whoami` /etc/passwd

In the above image we can see that the user nishant (current user) has home directory /home/nishant and the shell is /bin/sh

List your shells in Linux

Now to change the shell, first, we need to see which shells are installed on the system. We can check installed shells using the following command :

cat /etc/shells

This will show all shells as follows:

Before moving further, first understand who can change the user shell

  • Users can change shell to any other shell listed in /etc/shells/.
  • The root account can be used to change any other user login shell.
  • If an account has a restricted login shell, then only the root can change that user’s shell.

Changing default sh shell to bash

Using usermod command

usermod is a command that modifies the system account files. usemod can change the shell of Users by modifying file /etc/passwd. usermod command provides the -s or –shell option to change the user’s login shell.

In this example, we are going to change the shell of a user named nishant. We are going to change the shell from /bin/sh to /bin/bash of user nishant using usermod command.

sudo usermod --shell /bin/bash nishant

With usermod command mention shell and username after –shell option.

Now you can see the shell use changed. In the above commands, replace nishant with the user name whose shell has to change.

Using chsh Utility

chsh is the utility to change a user’s login shell. chsh provides the -s option to change the user’s shell. This method also modifies the file /etc/passwd. Use the following command to change shells using chsh:

chsh -s /bin/bash nishant

Change User Shell to /etc/passwd File

 As we see in the above two methods, the usermod command and chsh utility modify the /etc/passwd file and change the user shell. We can do that manually also by editing the /etc/passwd file. Just change the shell after the username and home directory in the /etc/passwd file and save the file.

nano /etc/passwd

Contents

  1. Introduction

    1. What is a shell?
    2. Short Description of the main shells
    3. Why change your shell
    4. Deciding on a shell
  2. How to Change Shells

    1. Temporarily changing your shell for the session you are in
    2. Changing your login shell which is permanent

      1. interactive method
      2. non-interactive method
  3. More information

Introduction

What is a shell?

A shell is a program that provides the traditional, text-only user interface for Unix-like operating systems. Its primary function is to read commands that are typed into a console (i.e., an all-text display mode) or terminal window (an all-text window) in a GUI (graphical user interface) and then execute (i.e., run) them.

Although bash, the default shell on many Debian based Linux distros like Ubuntu and Linux Mint, is highly versatile and can be used for almost anything, each shell has its own characteristics and there might be situations in which it is preferable to use some other shell, such as ash, csh, ksh, sh or zsh. For example, the csh shell has a syntax that resembles that of the highly popular C programming language, and thus it is sometimes preferred by programmers.

Short Description of the main shells

Bourne: the standard default shell for non root users in FreeBSD. You can read about the shell by looking at the «man sh» pages. Uses abbreviation sh.

Korn: a shell developed by AT &T. You can read more about it by looking at the «man ksh93» pages. Uses abbreviation ksh or ksh93.

Bash: The Bourne Again SHell. You can read about it in the «man bash» pages. Uses abbreviation bash.

Z-Shell: The Z shell. You can read about it by looking at the «man zsh» pages. Uses the abbreviation zsh.

C-Shell: The C shell. You can read about it by looking at the «man csh» pages. Uses the abbreviation csh.

TC-Shell: Basically the same thing as above. They are a little bit different, but not very much so they now fall into the same category. You can read about it by looking at the «man tcsh» pages. Uses the abbreviation tcsh.

How to find out what shell you are running:

type at prompt:

  $ echo $SHELL

Here is what you may see:

/bin/sh : This is the Bourne shell.

/bin/ksh93 : This is the Korn shell.

/bin/bash : This is the Bash shell.

/bin/zsh : This is the Z shell.

/bin/csh : This is the C Shell.

/bin/tcsh : This is the TC Shell.

Next Check on your Valid login Shells

  $ vi /etc/shells

Important Note: You May not have all of these installed on your system right now. The way I checked If a shell was installed my system was by looking to see if I had man pages for a particular shell. I will use csh as an example. Type this into your terminal.

  $ man csh

If you don’t have any man pages then there is a high probability you don’t have this shell on your system. There is one other way to test this. Type this into your terminal.

  $ csh
  $ ps

If you have csh installed on your system you will see something similar to this.

PID TTY          TIME CMD
13964 pts/0    00:00:00 bash
22450 pts/0    00:00:00 csh
22451 pts/0    00:00:00 ps

If you don’t have csh installed on your system then install it will this command.

  $ sudo apt-get install csh

Why change your shell

The UNIX shell is most people’s main access to the UNIX operating system and as such any improvement to it can result in considerably more effective use of the system, and may even allow you to do things you couldn’t do before. The primary improvement most of the new generation shells give you is increased speed. They require fewer key strokes to get the same results due to their completion features, they give you more information (e.g. showing your directory in your prompt, showing which files it would complete) and they cover some of the more annoying features of UNIX, such as not going back up symbolic links to directories.

Deciding on a shell

Which of the many shells you choose depends on many different things, here is what I consider to be the most important, you may think differently.

How much time do I have to learn a new shell?

  • There is no point in using a shell with a different syntax, or a completly different alias system if you havn’t the time to learn it. If you have the time and are presently using csh or tcsh it is worth considering a switch to a Bourne shell variant.

What do I wish to be able to do with my new shell?

  • The main reason for switching shells is to gain extra functionality; its vital you know what you are gaining from the switch.

Do I have to be able to switch back to a different shell?

  • If you may have to switch back to a standard shell, it is fairly important you don’t become too dependent on extra features and so can’t use an older shell.

How much extra load can the system cope with?

  • The more advanced shells tend to take up extra CPU, since they work in cbreak mode; if you are on an overloaded machine they should probably be avoided; this can also cause problems with an overloaded network. This only really applies to very old systems nowadays.

What support is given for my new shell?

  • If your new shell is not supported make sure you have someone you can ask if you encounter problems or that you have the time to sort them out yourself.

What shell am I using already?

  • Switching between certain shells of the same syntax is alot easier than switching between shells of a different syntax. So if you havn’t much time a simple upgrade (eg csh to tcsh) may be a good idea.

Can I afford any minor bugs?

  • Like most software all shells have some bugs in them (especially csh), can you afford the problems that may occur because of them.

How to Change Shells

There are two different methods of changing shells.

  1. Temporarily changing your shell for the session you are in.
  2. Changing your login shell which is permanent.

Temporarily changing your shell for the session you are in

I will use csh as again an example. I will assume you already have csh installed on your system. All you need to do is type the command below into your terminal.

  $ csh

There are a few ways to verify this. This first comes from above.

  $ ps

If you have csh installed on your system you will see something similar to this.

PID TTY          TIME CMD
13964 pts/0    00:00:00 bash
22450 pts/0    00:00:00 csh
22451 pts/0    00:00:00 ps

The second: Upon changing shells, a different command prompt (i.e., the short text message at the left of each command line) may be shown, depending on the previous and new shells. For example, if the original shell were bash and the new shell is sh, the command prompt would change for a user george from something like [george@localhost george]$ to something like sh-2.05b$.

To return to the original shell, or any other one for that matter, all that is necessary is to just type its name and then press the ENTER key. Thus, for example, to return to the bash shell from the sh shell (or from any other shell), all that is required is to type the word bash or exit.

Changing your login shell which is permanent

You will use a program called chsh. There is a interactive method and non-interactive method. Type this into your terminal.

interactive method

  $ chsh

This results in a brief dialog in which the user is prompted first for its password and then for the full path of the desired new shell.

Caution should be exercised when changing one’s default shell because it is possible to make an error that only the root user (i.e., system administrator) can repair (although it should be easy for a skilled user to repair it on a home system). In particular, it is important to first test the shell temporarily in the current session and then to make certain that a valid shell name is being entered when making the permanent change.

non-interactive method

I will use csh as again an example.

  $ chsh -s /bin/csh

The -s sets it for you without having to go into the editor to do it.

Okay you did the command and it went ok.but the echo says it is the same. Log out and back it for the change to take effect.Then do echo $SHELL. You should see it show the new shell.

More information

If you would like more information I recommend reading these websites.

http://www.linfo.org/change_shell.html http://www.softlab.ntua.gr/facilities/documentation/unix/shelldiff.html http://www.faqs.org/faqs/unix-faq/shell/shell-differences/ http://physics.nyu.edu/resources/login_shell.html http://www.geekvenue.net/chucktips/jason/chuck/1035144363/index_html

How is it possible to change the default shell? The env command currently says:

SHELL=/bin/tcsh

and I want to change that to Bash.

Matthias Braun's user avatar

asked Oct 24, 2012 at 9:15

mahmood's user avatar

2

Try linux command chsh.

The detailed command is chsh -s /bin/bash.
It will prompt you to enter your password.
Your default login shell is /bin/bash now. You must log out and log back in to see this change.

The following is quoted from man page:

The chsh command changes the user login shell. This determines the
name
of the users initial login command. A normal user may only change the
login shell for her own account, the superuser may change the login
shell for any account

This command will change the default login shell permanently.

Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh.

Elijah Lynn's user avatar

Elijah Lynn

11.8k10 gold badges58 silver badges86 bronze badges

answered Oct 24, 2012 at 9:21

Summer_More_More_Tea's user avatar

14

You can change the passwd file directly for the particular user or use the below command

chsh -s /usr/local/bin/bash username

Then log out and log in

answered Oct 24, 2012 at 9:24

Desert Ice's user avatar

Desert IceDesert Ice

4,3614 gold badges31 silver badges58 bronze badges

6

You should have a ‘skeleton’ somewhere in /etc, probably /etc/skeleton, or check the default settings, probably /etc/default or something. Those are scripts that define standard environment variables getting set during a login.

If it is just for your own account: check the (hidden) file ~/.profile and ~/.login. Or generate them, if they don’t exist. These are also evaluated by the login process.

answered Oct 24, 2012 at 9:21

arkascha's user avatar

arkaschaarkascha

41.1k7 gold badges55 silver badges89 bronze badges

3

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

Некоторые из оболочек предоставляют дополнительные функции для удобства пользователе. Возьмем, к примеру, оболочку Fish. Онf частично начинает показывать вам подсказки команд, основанные на вашей предыдущей набранной команде. Это очень удобно, если вы не хотите постоянно помнить ярлыки на терминале Linux.

Давайте посмотрим некоторые моменты оболочки системы Linux.

Чтобы узнать, какая оболочка по умолчанию установлена в конкретной системе, проверим переменную среды SHELL. Обычно оболочкой по умолчанию является bash, и она отображается так:

$ echo $SHELL
/bin/bash

Не существует единого метода, который бы сообщал вам, какая оболочка используется в данный момент со 100%-ой точностью.
Но можно попробовать либо echo $0, который показывает вывод, подобный этому:

$ echo $0
zsh

либо проверить процесс, используя ps -p $$ следующим образом:

$ ps -p $$

  PID TTY          TIME CMD

 9625 pts/0    00:00:00 zsh

Все оболочки, доступные в конкретной системе, перечислены в файле /etc/shells. Можно использовать команды cat или less для просмотра содержимого файла.

$ less /etc/shells
# /etc/shells: valid login shells
/bin/sh
/bin/bash
/bin/rbash
/bin/dash
/usr/bin/tmux
/usr/bin/fish
/bin/zsh
/usr/bin/zsh

Если вы хотите использовать другую оболочку, вы можете просто ввести ее имя и войти в новую оболочку. Например, если вы хотите использовать Z Shell (zsh), вы можете использовать:

$ zsh

Чтобы выйти из новой оболочки и вернуться к предыдущей достаточно выполнить команду exit.

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

Linux позволяет изменить оболочку по умолчанию с помощью команды chsh. Лучший способ изменить оболочку по умолчанию для вошедшего в систему пользователя — сменить имя оболочки, указанное в файле /etc/shells, с помощью опции -s.

# chsh -s /usr/bin/fish

Для того, чтобы изменения вступили в силу необходимо выйти из системы, иначе создастся ощущение, что запуск chsh не изменил оболочку.

Необходимо указывать полный путь к файлу /etc/shells? Если использовать chsh -s fish, то получим ошибку типа chsh: fish не является допустимой оболочкой.

Источник

Asked
11 years, 5 months ago

Viewed
191k times

I have csh as my default shell, as shown by echo $SHELL. I want to switch to bash as my default shell. I tried the following approaches to no avail:

  1. With chsh I get:

    chsh: can only change local entries; use ypchsh instead.
    
  2. With ypchsh I get:

    ypchsh: yppasswdd not running on NIS master host ("dcsun2").
    

I only have .chsrc in my home directory and I cannot find any .profile files in /etc. How can I change my default shell to bash?

Kusalananda's user avatar

Kusalananda

307k35 gold badges598 silver badges896 bronze badges

asked Sep 13, 2011 at 15:27

Sumod's user avatar

1

  1. Make sure you’ve got bash installed.

  2. Learn the location of bash:

    which bash
    

    or

    whereis bash
    

    Below, I’ll assume the location is /bin/bash.

    a) If you have administrative rights, just run as root:

    usermod -s /bin/bash YOUR_USERNAME
    

    (replacing YOUR_USERNAME with your user name).

    b) If you don’t have adm. rights, you can still just run bash --login at login, by putting the below line at the end of your .cshrc or .profile (in your home directory) :

    setenv SHELL /bin/bash
    exec /bin/bash --login
    

aseagram's user avatar

answered Sep 13, 2011 at 16:13

rozcietrzewiacz's user avatar

rozcietrzewiaczrozcietrzewiacz

38k8 gold badges91 silver badges102 bronze badges

12

Contact your system administrator. He’s set things up wrong. If you are your system administrator then you’ve set things up wrong.

The error message looks pretty straight forward. You don’t have yppasswd running on dcsun2. It should be.

But doing a quick google search comes up with this result which indicates that you’ll get this error if yppasswd is running on both the client and the server. In this case turn it off on the client.


If you’re stuck with csh as your login shell, you can still make it invoke bash when you log in. Put the following commands in your ~/.login (see also Changing the default shell without chsh or administrator priviledges):

sleep 2
if (-x /usr/local/bin/bash) then
  exec /usr/local/bin/bash -l
endif

Replace /usr/local/bin/bash by the proper path if necessary. If everything works, remove sleep 2 (which puts a delay during which you can press Ctrl+C to drop to a csh prompt, in case something goes wrong).

Community's user avatar

answered Sep 13, 2011 at 15:45

bahamat's user avatar

bahamatbahamat

37.5k4 gold badges70 silver badges103 bronze badges

Понравилась статья? Поделить с друзьями:
  • Как изменить psi на bar киа k5
  • Как изменить psd на pdf
  • Как изменить ps1
  • Как изменить prt sc
  • Как изменить proxy сервер