Arch linux which shell

Command-line shell

A Unix shell is a command-line interpreter or shell that provides a traditional user interface for the Unix operating system and for Unix-like systems. Users direct the operation of the computer by entering commands as text for a command line interpreter to execute or by creating text scripts of one or more such commands.

Contents

List of shells

Shells that are more or less POSIX compliant are listed under #POSIX compliant, while shells that have a different syntax are under #Alternative shells.

POSIX compliant

These shells can all be linked from /usr/bin/sh . When Bash, mksh AUR and zsh are invoked with the sh name, they automatically become more POSIX compliant.

  • Bash — Bash extends the Bourne shell with command-line history and completion, indexed and associative arrays, integer arithmetic, process substitution, here strings, regular expression matching and brace expansion.

https://www.gnu.org/software/bash/ || bash

  • Dash — Descendant of the NetBSD version of the Almquist SHell (ash). A fast POSIX-compliant shell that aims to be as small as possible.

http://gondor.apana.org.au/

herbert/dash/ || dash

  • KornShell (ksh) — The KornShell language is a complete, powerful, high-level programming language for writing applications, often more easily and quickly than with other high-level languages. This makes it especially suitable for prototyping. ksh has the best features of the Bourne shell and the C shell, plus many new features of its own. Thus ksh can do much to enhance your productivity and the quality of your work, both in interacting with the system, and in programming. ksh programs are easier to write, and are more concise and readable than programs written in a lower level language such as C.

http://www.kornshell.com || See the article.

  • OSH (Oil Shell) — Oil Shell is a Bash-compatible UNIX command-line shell. OSH can be run on most UNIX-like operating systems, including GNU/Linux. It is written in Python (v2.7), but ships with a native executable. The dialect of Bash recognized by OSH is called the OSH language.

https://www.oilshell.org || oshAUR

  • Yash — Yet another shell, is a POSIX-compliant command line shell written in C99 (ISO/IEC 9899:1999). Yash is intended to be the most POSIX-compliant shell in the world while supporting features for daily interactive and scripting use.

https://yash.osdn.jp || yashAUR

  • Zsh — Shell designed for interactive use, although it is also a powerful scripting language. Many of the useful features of Bash, ksh, and tcsh were incorporated into Zsh; many original features were added. The introductory document details some of the unique features of Zsh.

https://www.zsh.org/ || zsh

Alternative shells

  • C shell (tcsh) — Command language interpreter usable both as an interactive login shell and a shell script command processor. It includes a command-line editor, programmable word completion, spelling correction, a history mechanism, job control and a C-like syntax.

https://www.tcsh.org || tcsh

  • Elvish — Elvish is a modern and expressive shell, that can carry internal structured values through pipelines. This feature makes possible avoiding a lot of complex text processing code. It features an expressive programming language, with features like exceptions, namespacing and anonymous functions. It also has a powerful readline which checks the syntax while typing, and syntax highlighting by default.

https://elv.sh || elvish

  • fish — Smart and user-friendly command line shell. Fish performs full-color command line syntax highlighting, as well as highlighting and completion for commands and their arguments, file existence, and history. It supports complete-as-you-type for history and commands. Fish is able to parse the system’s man pages in order to determine valid arguments for commands, allowing it to highlight and complete commands. Easy last-command revision can be done using Alt+Up . The fish daemon (fishd) facilitates synchronized history across all instances of fish, as well as universal and persistent environment variables. Additionally, fish features significantly simplified programming syntax and control flow (similar to ruby). For more information, see the tutorial.
Читайте также:  Как восстановить стандартный загрузчик windows

https://fishshell.com/ || fish

  • ion — Ion is a modern system shell that features a simple, yet powerful, syntax. It is written entirely in Rust, which greatly increases the overall quality and security of the shell, eliminating the possibilities of a ShellShock-like vulnerability, and making development easier. It also offers a level of performance that exceeds that of Dash, when taking advantage of Ion’s features. While it is developed alongside, and primarily for, RedoxOS, it is a fully capable on other *nix platforms. For more details lookup its manual.

https://gitlab.redox-os.org/redox-os/ion/ || ion-gitAUR

  • Nash — Nash is a system shell, inspired by plan9 rc, that makes it easy to create reliable and safe scripts taking advantages of operating systems namespaces (on linux and plan9) in an idiomatic way.

https://github.com/NeowayLabs/nash || nash-gitAUR

  • nushell — Nu draws inspiration from functional programming languages, and modern CLI tools. Rather than thinking of files and services as raw streams of text, Nu looks at each input as something with structure.

https://www.nushell.sh || nushell

  • Oh — Unix shell written in Go. It is similar in spirit but different in detail from other Unix shells. Oh extends the shell’s programming language features without sacrificing the shell’s interactive features.

https://github.com/michaelmacinnis/oh || oh-gitAUR

  • PowerShell — PowerShell is an object-oriented programming language and interactive command line shell, originally written for and exclusive to Windows. Later on, it was open sourced and ported to macOS and Linux.

https://github.com/PowerShell/PowerShell || powershellAUR

  • rc — Command interpreter for Plan 9 that provides similar facilities to UNIX’s Bourne shell, with some small additions and less idiosyncratic syntax.

http://doc.cat-v.org/plan_9/4th_edition/papers/rc || 9base

  • xonsh — Python-powered shell with additional shell primitives that you are used to from Bash and IPython.

https://xon.sh/ || xonsh

Changing your default shell

After installing one of the above shells, you can execute that shell inside of your current shell, by just running its executable. If you want to be served that shell when you login however, you will need to change your default shell.

To list all installed shells, run:

And to set one as default for your user do:

If you are using systemd-homed, run:

where full-path-to-shell is the full path as given by chsh -l .

If you now log out and log in again, you will be greeted by the other shell.

Login shell

A login shell is an invocation mode, in which the shell reads files intended for one-time initialization, such as system-wide /etc/profile or the user’s

/.profile or other shell-specific file(s). These files set up the initial environment, which is inherited by all other processes started from the shell (including other non-login shells or graphical programs). Hence, they are read only once at the beginning of a session, which is, for example, when the user logs in to the console or via SSH, changes the user with sudo or su using the —login parameter, or when the user manually invokes a login shell (e.g. by bash —login ).

See #Configuration files and the links therein for an overview of the various initialization files. For more information about login shell, see also Difference between Login Shell and Non-Login Shell? and Why a «login» shell over a «non-login» shell? on Stackexchange.

Configuration files

To autostart programs in console or upon login, you can use shell startup files/directories. Read the documentation for your shell, or its ArchWiki article, e.g. Bash#Configuration files or Zsh#Startup/Shutdown files.

Читайте также:  Обработка сигналов c linux

See also Wikipedia:Unix shell#Configuration files for a comparison of various configuration files of various shells.

/etc/profile

Upon login, all Bourne-compatible shells source /etc/profile , which in turn sources any readable *.sh files in /etc/profile.d/ : these scripts do not require an interpreter directive, nor do they need to be executable. They are used to set up an environment and define application-specific settings.

Standardisation

It is possible to make (some) shells configuration files follow the same naming convention, as well as supporting some common configuration between the shells.

Input and output

  • Redirections truncate files before commands are executed: will therefore not work as expected. While some commands (sed for example) provide an option to edit files in-place, many do not. In such cases you can use the sponge(1) command from the moreutils package.
  • Because cat is not built into the shell, on many occasions you may find it more convenient to use a redirection, for example in scripts, or if you care a lot about performance. In fact does the same as cat file .
  • POSIX-compliant shells support Here Documents:
  • Shell pipelines operate on stdout by default. To operate on stderr(3) you can redirect stderr to stdout with command 2>&1 | othercommand or, for Bash 4, command |& othercommand .
  • Remember that many GNU core utilities accept files as arguments, so for example grep pattern is replaceable with grep patternfile .

Источник

Command-line shell (Русский)

Кома́ндная оболо́чка UNIX (англ. Unix shell, часто просто «шелл» или «sh») — командный интерпретатор, используемый в операционных системах семейства UNIX, в котором пользователь может либо давать команды операционной системе по отдельности, либо запускать скрипты, состоящие из списка команд. В первую очередь, под shell понимаются POSIX-совместимые оболочки, восходящие к Bourne shell (шелл Борна), появившемуся в Unix Version 7.

Список оболочек

  • Bash — (от англ. Bourne again shell, каламбур «Born again» shell — «возрождённый» shell) — усовершенствованная и модернизированная вариация командной оболочки Bourne shell. Одна из наиболее популярных современных разновидностей командной оболочки UNIX. Особенно популярна в среде Linux, где она часто используется в качестве предустановленной командной оболочки.

Bash — это командный процессор, работающий, как правило, в интерактивном режиме в текстовом окне. Bash также может читать команды из файла, который называется скриптом (или сценарием). Как и все Unix-оболочки, он поддерживает автодополнение имён файлов и директорий, подстановку вывода результата команд, переменные, контроль за порядком выполнения, операторы ветвления и цикла. Ключевые слова, синтаксис и другие основные особенности языка были заимствованы из sh. Другие функции, например, история, были скопированы из csh и ksh. Bash в основном удовлетворяет стандарту POSIX, но с рядом расширений. Кроме того, большинство сценариев SH можно запустить в Bash без изменений.

https://www.gnu.org/software/bash/ || bash

  • C shell — C shell (csh) — командная оболочка UNIX со встроенным скриптовым языком, разработанная Биллом Джоем, активным разработчиком BSD UNIX и создателем редактора vi, в 1979 году.

Базировался на коде командного интерпретатора шестой версии UNIX. Скриптовый язык не уступает шеллу Борна по мощности, но отличается синтаксисом. В то время как Борн скопировал все основные операторы с языка Алгол 68, Билл Джой использовал в качестве макета язык Си, вероятно, руководствуясь своими предпочтениями и предпочтениями других пользователей BSD UNIX. В начале 1990-х C shell подвергся большой критике за свою двусмысленность и немногословность интерпретатора, останавливающего выполнение скрипта, но не сообщающего никаких подробностей о том, что же всё-таки произошло. Порой скрипты csh работали совсем не так, как этого ожидал пользователь. Также встречались ситуации, когда интерпретатор отбраковывал, казалось бы, непротиворечивые строки кода. C shell вошёл в поставку 4.1BSD и до сих пор остаётся базовой частью всех её потомков, в том числе FreeBSD и OpenBSD.

https://www.tcsh.org || tcsh

  • DASH — POSIX-совместимая реализация /bin/sh стремящаяся быть более компактной. Dash делает это без ущерба для быстродействия, где это возможно.
Читайте также:  Linux in your browser

На самом деле, он значительно быстрее, чем Bash (the GNU Bourne-Again SHell) для большинства задач.

herbert/dash/ || dash

  • fish — Умная и удобная коммандная оболочка (развивающаяся как более дружественная к пользователю альтернатива bash и zsh). Fish делает полную цветную подсветку синтаксиса командной строки, а также подсветку завершения команд и их аргументов, существующих файлов, и истории. С автоматическим выявлением ошибок ввода, предложеним возможных вариантов ввода на основе истории прошлых операций, автодополнение ввода опций и команд с использованием их описания в man-руководствах, комфортнаю работу из коробки без необходимости дополнительной настройки, упрощённый язык написания сценариев, поддержку буфера обмена X11, удобные средства поиска в истории выполненных операций. Легкий просмотр последних команд может быть сделан с помощью Alt-Up. Демон Fish (fishd) облегчает синхронизирование истории во всех случаях использовнаия fish, а также универсальных и постоянных переменных сред.

https://fishshell.com/ || fish

  • Korn shell — Командная оболочка UNIX. Имеет полную обратную совместимость с Bourne shell и включает в себя возможности C shell. Язык KornShell представляет собой полный, мощный язык программирования высокого уровня, для написания приложений. Зачастую легче и быстрее, чем на других языках высокого уровня. Это делает его особенно подходящим для прототипирования. Ksh имеет лучшие черты оболочки Bourne и C, плюс множество самостоятельных возможностей. Таким образом Ksh может сделать многое, чтобы повысить производительность и качество вашей работы в взаимодействии с системой и в программировании. Ksh программы легче писать, они более кратки и читабельны, чем программы написанные на языке нижнего уровня, такого как C.

http://www.kornshell.com || Смотрите Ksh#Installation

  • Oh — Unix оболочка, написанная на Go. Это оболочка в духе Unix, но отличается различными деталями. Oh расширяет возможности языка программирования оболочки без ущерба интерактивных функций оболочки.

https://github.com/michaelmacinnis/oh || oh-gitAUR

  • rc — Командный интерпретатор для Plan 9, который предоставляет анологичные средства оболочки Bourne для UNIX. С небольшими дополнениями и менее своеобразным синтаксисом.

http://plan9.bell-labs.com/sys/doc/rc.html [устаревшая ссылка 2020-08-02] || 9base-gitAUR

  • Zsh — Оболочка предназначена для интерактивного использования, хотя это такойже мощный скриптовый язык. Многие из полезных особенностей Bash, Ksh и Tcsh были включены в Zsh; были добавлены многие оригинальные черты. Страничка вводный документ перечислены некоторые из уникальных особенностей Zsh

https://www.zsh.org/ || zsh

из Wikipedia Zsh Это одна из современных командных оболочек UNIX, может использоваться как интерактивная оболочка, либо как мощный скриптовой интерпретатор. Zsh является расширенным bourne shell с большим количеством улучшений. Первая версия zsh была написана Паулем Фалстадом (Paul Falstad) в 1990 году, когда он был студентом Принстонского университета. Название ZSH произошло от университетского ассистента по имени Чжун Шао (Zhong Shao). Пол подумал, что учётная запись Чжуна, «zsh», будет хорошим названием для командной оболочки[1]. Сейчас развивается энтузиастами, под руководством Петера Стефенсона (Peter Stephenson) в рамках свободного проекта. Некоторые полезные особенности:

  1. Программируемое автодополнение, которое помогает пользователям вводить как команды, так и их аргументы, со встроенной поддержкой нескольких сотен команд;
  2. Разделяет историю команд между всеми запущенными экземплярами оболочки;
  3. Расширенное дополнение названий файлов, что позволяет указать файл без необходимости запускать внешние программы, наподобие find;
  4. Расширенная поддержка переменных и массивов;
  5. Редактирование многострочных команд в едином буфере;
  6. Коррекция опечаток;
  7. Имеет различные режимы совместимости (то есть, вы можете использовать zsh вместо bourne shell при запуске, как /bin/sh);
  8. Модифицируемые приглашения (prompts), включающие возможность расположить приглашение справа и настроить автоскрытие при наборе длинных команд;

Выбор оболочки по умолчанию

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

Посмотрите все установленные оболочки:

И установить одну по умолчанию для вашего пользователя (убедитесь, что вы используете полный путь, какой выдала команда chsh -l ):

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

Источник

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