What is the shell in linux

Unix / Linux — What is Shells?

A Shell provides you with an interface to the Unix system. It gathers input from you and executes programs based on that input. When a program finishes executing, it displays that program’s output.

Shell is an environment in which we can run our commands, programs, and shell scripts. There are different flavors of a shell, just as there are different flavors of operating systems. Each flavor of shell has its own set of recognized commands and functions.

Shell Prompt

The prompt, $, which is called the command prompt, is issued by the shell. While the prompt is displayed, you can type a command.

Shell reads your input after you press Enter. It determines the command you want executed by looking at the first word of your input. A word is an unbroken set of characters. Spaces and tabs separate words.

Following is a simple example of the date command, which displays the current date and time −

You can customize your command prompt using the environment variable PS1 explained in the Environment tutorial.

Shell Types

In Unix, there are two major types of shells −

Bourne shell − If you are using a Bourne-type shell, the $ character is the default prompt.

C shell − If you are using a C-type shell, the % character is the default prompt.

The Bourne Shell has the following subcategories −

  • Bourne shell (sh)
  • Korn shell (ksh)
  • Bourne Again shell (bash)
  • POSIX shell (sh)

The different C-type shells follow −

  • C shell (csh)
  • TENEX/TOPS C shell (tcsh)

The original Unix shell was written in the mid-1970s by Stephen R. Bourne while he was at the AT&T Bell Labs in New Jersey.

Bourne shell was the first shell to appear on Unix systems, thus it is referred to as «the shell».

Bourne shell is usually installed as /bin/sh on most versions of Unix. For this reason, it is the shell of choice for writing scripts that can be used on different versions of Unix.

In this chapter, we are going to cover most of the Shell concepts that are based on the Borne Shell.

Shell Scripts

The basic concept of a shell script is a list of commands, which are listed in the order of execution. A good shell script will have comments, preceded by # sign, describing the steps.

There are conditional tests, such as value A is greater than value B, loops allowing us to go through massive amounts of data, files to read and store data, and variables to read and store data, and the script may include functions.

We are going to write many scripts in the next sections. It would be a simple text file in which we would put all our commands and several other required constructs that tell the shell environment what to do and when to do it.

Shell scripts and functions are both interpreted. This means they are not compiled.

Example Script

Assume we create a test.sh script. Note all the scripts would have the .sh extension. Before you add anything else to your script, you need to alert the system that a shell script is being started. This is done using the shebang construct. For example −

This tells the system that the commands that follow are to be executed by the Bourne shell. It’s called a shebang because the # symbol is called a hash, and the ! symbol is called a bang.

To create a script containing these commands, you put the shebang line first and then add the commands −

Shell Comments

You can put your comments in your script as follows −

Save the above content and make the script executable −

The shell script is now ready to be executed −

Upon execution, you will receive the following result −

Note − To execute a program available in the current directory, use ./program_name

Extended Shell Scripts

Shell scripts have several required constructs that tell the shell environment what to do and when to do it. Of course, most scripts are more complex than the above one.

The shell is, after all, a real programming language, complete with variables, control structures, and so forth. No matter how complicated a script gets, it is still just a list of commands executed sequentially.

The following script uses the read command which takes the input from the keyboard and assigns it as the value of the variable PERSON and finally prints it on STDOUT.

Источник

What is «the Shell»?

Simply put, the shell is a program that takes commands from the keyboard and gives them to the operating system to perform. In the old days, it was the only user interface available on a Unix-like system such as Linux. Nowadays, we have graphical user interfaces (GUIs) in addition to command line interfaces (CLIs) such as the shell.

Читайте также:  Квесты windows для детей

On most Linux systems a program called bash (which stands for Bourne Again SHell, an enhanced version of the original Unix shell program, sh , written by Steve Bourne) acts as the shell program. Besides bash , there are other shell programs available for Linux systems. These include: ksh , tcsh and zsh .

What’s a «Terminal?»

It’s a program called a terminal emulator. This is a program that opens a window and lets you interact with the shell. There are a bunch of different terminal emulators we can use. Some Linux distributions install several. These might include gnome-terminal , konsole , xterm , rxvt , kvt , nxterm , and eterm .

Starting a Terminal

Window managers usually have a way to launch a terminal from the menu. Look through the list of programs to see if anything looks like a terminal emulator. While there are a number of different terminal emulators, they all do the same thing. They give us access to a shell session. You will probably develop a preference for one, based on the different bells and whistles it provides.

Testing the Keyboard

OK, let’s try some typing. Bring up a terminal window. The first thing we should see is a shell prompt that contains our user name and the name of the machine followed by a dollar sign. Something like this:

Excellent! Now type some nonsense characters and press the enter key.

If all went well, we should have gotten an error message complaining that it cannot understand the command:

Wonderful! Now press the up-arrow key. Watch how our previous command «kdkjflajfks» returns. Yes, we have command history. Press the down-arrow and we get the blank line again.

Recall the «kdkjflajfks» command using the up-arrow key if needed. Now, try the left and right-arrow keys. We can position the text cursor anywhere in the command line. This allows us to easily correct mistakes.

You’re not operating as root, are you?

If the last character of your shell prompt is # rather than $, you are operating as the superuser. This means that you have administrative privileges. This can be dangerous, since you are able to delete or overwrite any file on the system. Unless you absolutely need administrative privileges, do not operate as the superuser.

Using the Mouse

Even though the shell is a command line interface, the mouse is still handy.

Besides using the mouse to scroll the contents of the terminal window, we can can use it to copy text. Drag the mouse over some text (for example, «kdkjflajfks» right here on the browser window) while holding down the left button. The text should highlight. Release the left button and move the mouse pointer to the terminal window and press the middle mouse button (alternately, press both the left and right buttons at the same time when working on a touch pad). The text we highlighted in the browser window should be copied into the command line.

A few words about focus.

When you installed your Linux system and its window manager (most likely Gnome or KDE), it was configured to behave in some ways like that legacy operating system.

In particular, it probably has its focus policy set to «click to focus.» This means that in order for a window to gain focus (become active) you have to click in the window. This is contrary to traditional X Window behavior. You should consider setting the focus policy to «focus follows mouse». You may find it strange at first that windows don’t raise to the front when they get focus (you have to click on the window to do that), but you will enjoy being able to work on more than one window at once without having the active window obscuring the other. Try it and give it a fair trial; I think you will like it. You can find this setting in the configuration tools for your window manager.

Further Reading

  • The Wikipedia entry for Steve Bourne, developer of the original Bourne shell
  • The Wikipedia article on the Unix shell, the place where all this fun got started
  • The «Power Terminals» Adventure

© 2000-2021, William E. Shotts, Jr. Verbatim copying and distribution of this entire article is permitted in any medium, provided this copyright notice is preserved.

Linux® is a registered trademark of Linus Torvalds.

Источник

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).
Читайте также:  Cisco usb console driver x64 windows 10 download

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?

Обновл. 27 Июл 2021 |

В этой статье мы разберемся, что такое shell и зачем это нужно, а также рассмотрим наиболее часто используемые командные оболочки в Linux и Unix.

Что такое shell?

Shell (или «шелл», «командная оболочка») — это не только командный интерпретатор, который обеспечивает интерфейс взаимодействия между пользователем и ядром операционной системы, но и своеобразный язык программирования, в котором присутствуют такие конструкции, как операторы условного ветвления, циклы, переменные и многое другое.

Операционная система (ОС) запускает командную оболочку для каждого пользователя, когда тот входит в систему или открывает окно терминала. Первым что пользователь увидит в окне терминала, будет приглашение оболочки — оно, как правило, состоит из имени пользователя и имени хоста, отделенные друг от друга символом @ , следом за ними идет путь текущей рабочей директории и один из двух символов: $ или # .

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

Окно терминала обычного пользователя (виден символ $)

Окно терминала привилегированного (root) пользователя (виден символ #)

Примечание: Знак тильды (

) указывает на то, что мы находимся в домашнем каталоге текущего пользователя.

После приглашения, пользователь вводит различные команды в терминал, оболочка запускает программы для пользователя, а затем отображает в терминале результат их выполнения. Команды могут быть либо введены непосредственно самим пользователем, либо считаны из файла, называемого shell-скриптом или shell-программой.

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

Внутренние и внешние команды оболочки

Вводимые пользователем команды делятся на два типа:

Внутренние — это команды, изначально встроенные в оболочку.

Внешние — это команды, которые не встроены в оболочку. По своей сути они являются скорее небольшими отдельными программами, расположенными где-то в файловой системе (обычно, в каталогах /bin или /usr/bin).

Чтобы определить тип команды, достаточно в окне терминала ввести type :

Читайте также:  Windows loader by daz не могу активировать

Как вы можете видеть, команды dirs , pwd , cd и true — являются внутренними командами оболочки bash. А вот команды uname , id и whereis — являются внешними, т.к. они ссылаются на соответствующие файлы в каталоге /usr/bin.

Ознакомиться с полным списком внутренних команд оболочки можно при помощи команды help :

Как узнать какая оболочка у меня установлена?

Если вы только начинаете свое знакомство с Linux и не меняли оболочку, то наиболее вероятно, что в вашей системе используется bash. Самый простой способ узнать, какая оболочка используется в данный момент — это обратиться к переменной окружения SHELL :

Кроме того, можно задействовать команду ps –p $$ , возвращающую информацию о процессе с заданным идентификатором. В нашем случае, идентификатором оболочки являются символы $$ :

Не трудно заметить, что в настоящее время используется оболочка bash. Для просмотра всех доступных оболочек в вашей системе, необходимо обратиться к содержимому файла /etc/shells:

Типы командных оболочек

В *nix-системах существует два основных типа оболочек: оболочки на основе Bourne shell и оболочки на основе C shell.

Типичными представителями оболочек типа Bourne shell являются:

sh (Bourne shell)

bash (Bourne Again shell)

К оболочкам типа C Shell относятся:

tcsh (TENEX/TOPS C shell)

Ниже представлены некоторые из самых распространенных шеллов, используемых в *nix-системах:

Примечание: Термин «*nix-системы» обозначает Unix-подобные операционные системы.

sh (Bourne shell)

sh (сокр. от «Bourne shell») — это самая старая (среди рассматриваемых) оболочка, написанная Стивеном Борном из AT&T Bell Labs для ОС UNIX v7. Оболочка доступна практически в любом *nix-дистрибутиве. Многие другие шеллы уходят своими корнями именно к sh. Благодаря своей скорости работы и компактности, данная оболочка является предпочтительным средством для написания shell-скриптов. К её недостаткам можно отнести отсутствие функций для использования оболочки в интерактивном режиме, а также отсутствие встроенной обработки арифметических и логических выражений.

Примечание: Стоит отметить, что из-за общего морального устаревания оболочки, в современных системах ссылка на шелл sh (/bin/sh), обычно, является псевдонимом для запуска текущей, более новой оболочки.

Характерные черты sh:

Полные пути к интерпретатору: /bin/sh и /sbin/sh.

Приглашение для обычного пользователя: $ .

Приглашение для суперпользователя (root): # .

bash (Bourne-Again shell)

bash (сокр. от «Bourne–Again shell») — это усовершенствованный и дополненный вариант шелла sh, является одной из самых популярных современных командных оболочек *nix-систем.

Объединяет в себе полезные фишки оболочек ksh и csh.

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

Характерные черты bash:

Полный путь к интерпретатору: /bin/bash.

Приглашение для обычного пользователя: имя_пользователя@имя_хоста:

— это домашний каталог текущего пользователя, например, mrsmith@mypc:

Приглашение для суперпользователя (root): root@имя_хоста:

ksh (Korn shell)

ksh (сокр. от «Korn shell») — это командная оболочка, разработанная Дэвидом Корном из AT&T Bell Labs в 1980-x годах.

Является расширением sh.

Имеет обратную совместимость с sh.

Имеет интерактивный функционал, сравнимый с csh.

Включает в себя удобные для программирования функции, такие как: встроенную поддержку арифметических выражений/функций, Си-подобный синтаксис скриптов и средства для работы со строками.

Работает быстрее, чем csh.

Может запускать скрипты, написанные для sh.

Характерные черты ksh:

Полный путь к интерпретатору: /bin/ksh.

Приглашение для обычного пользователя: $ .

Приглашение для суперпользователя (root): # .

csh (C shell)

csh (сокр. от «C shell») — это командная оболочка, созданная Биллом Джоем (автором редактора vi) с целью усовершенствования стандартного шелла Unix (sh).

Имеет встроенные функции для интерактивного использования, например, псевдонимы (aliases) и историю команд.

Включает в себя удобные для программирования функции, такие как: встроенную поддержку арифметических выражений и Cи-подобный синтаксис скриптов.

Характерные черты csh:

Полный путь к интерпретатору: /bin/csh.

Приглашение для обычного пользователя: % .

Приглашение для суперпользователя (root): # .

tcsh (TENEX C Shell)

tcsh (сокр. от «TENEX C shell») — это командная оболочка, созданная Кэном Гриром, которая позиционируется как улучшенная версия шелла csh.

Имеет полную совместимость csh.

Именно в данном шелле впервые появилась функция автодополнения команд и путей.

Удобна для интерактивной работы.

Поддерживает редактор командной строки в стиле vi или emacs.

Является стандартным шеллом во FreeBSD.

Характерные черты tcsh:

Полный путь к интерпретатору: /bin/tcsh.

Приглашение для обычного пользователя: имя_хоста:

Приглашение для суперпользователя (root): # .

zsh (Z Shell)

zsh (сокр. от «Z shell») — это командная оболочка, созданная Паулем Фалстадом во время его учебы в Принстонском университете, позиционируется как свободная современная sh-совместимая командная оболочка.

Среди стандартных шеллов больше всего похожа на ksh, но включает в себя множество улучшений.

Встроенная поддержка программируемого автодополнения команд, имен файлов и пр.

Поддержка проверки орфографии и опечаток.

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

Характерные черты zsh:

Полный путь к интерпретатору: /bin/zsh.

Приглашение для обычного пользователя: имя_хоста% .

Приглашение для суперпользователя (root): root@имя_хоста:

Резюмируем

Краткая сводная таблица для 6 вышерассмотренных командных оболочек:

Командная оболочка Путь Приглашение (обычный пользователь) Приглашение (root)
sh (Bourne Shell) /bin/sh и /sbin/sh $ #
bash (Bourne-Again Shell) /bin/bash имя_пользователя@имя_хоста:

$ имя_пользователя@имя_хоста:

# ksh (Korn Shell) /bin/ksh $ # csh (C Shell) /bin/csh % # tcsh (TENEX C Shell) /bin/tcsh имя_хоста:

> # zsh (Z Shell) /bin/zsh % #

Примечание: Помимо представленных выше оболочек, есть еще и такие оболочки, как:

mksh — оболочка, основной упор в которой сделан на написание скриптов;

dash — более легковесная в сравнении с bash оболочка, но из-за этого обладающая ограниченной функциональностью;

fish — «новая» оболочка, написанная в 2005 году, отличительной чертой которой является упор на комфорт использования и упрощение командного языка;

Поделиться в социальных сетях:

Источник

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