- Unix / Linux — What is Shells?
- Shell Prompt
- Shell Types
- Shell Scripts
- Example Script
- Shell Comments
- Extended Shell Scripts
- 3 Ways to Change a Users Default Shell in Linux
- 1. usermod Utility
- 2. chsh Utility
- 3. Change User Shell in /etc/passwd File
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Как определить и изменить командную оболочку (shell) в Linux
- Что такое командная оболочка
- Оболочки Linux
- Как определить текущую командую оболочку
- Способ 1
- Способ 2
- Способ 3
- Как посмотреть список оболочек, доступных в системе
- Как временно переключиться на другую оболочку
- Как изменить оболочку
- Заключение
- UNIX / Linux : What Is a Shell? What are different Shells?
- What Is a Shell?
- User Environment
- What are the different Shells?
- 1. The Bourne Shell
- 2. The C Shell
- 3. The Korn Shell
- 4. The GNU Bourne-Again Shell
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.
Источник
3 Ways to Change a Users Default Shell in Linux
In this article, we will describe how to change a user’s shell in Linux. The shell is a program that accepts and interprets commands; there are several shells such as bash, sh, ksh, zsh, fish and many other lesser known shells available on Linux.
Bash (/bin/bash) is a popular shell on most if not all Linux systems, and it’s normally the default shell for user accounts.
There are several reasons for changing a user’s shell in Linux including the following:
- To block or disable normal user logins in Linux using a nologin shell.
- Use a shell wrapper script or program to login user commands before they are sent to a shell for execution. Here, you specify the shell wrapper as a user’s login shell.
- To meet a user’s demands (wants to use a specific shell), especially those with administrative rights.
When creating user accounts with the useradd or adduser utilities, the —shell flag can be used to specify the name of a user’s login shell other than that specified in the respective configuration files.
A login shell can be accessed from a text based interface or via a SSH from remote Linux machine. However, if you login via a graphical user interface (GUI), you can access the shell from a terminal emulators like xterm, konsole and many more.
Let’s first list all available shells on your Linux system, type.
Before you proceed any further, note that:
- A user can change their own shell to any thing: which, however must be listed in the /etc/shells file.
- Only root can run a shell not listed in /etc/shells file.
- If an account has a restricted login shell, then only root can change that user’s shell.
Now let’s discuss three different ways to change Linux user shell.
1. usermod Utility
usermod is a utility for modifying a user’s account details, stored in the /etc/passwd file and the -s or —shell option is used to change the user’s login shell.
In this example, we’ll first check user tecmint’s account information to view his default login shell and then change its login shell from /bin/sh to /bin/bash as follows.
Change User Shell using Usermod
2. chsh Utility
chsh is a command line utility for changing a login shell with the -s or –shell option like this.
Change User Shell Using chsh
The two methods above all modify the shell specified in /etc/passwd file which you can edit manually as in the third method below.
3. Change User Shell in /etc/passwd File
In this method, simply open the /etc/passwd file using any of your favorite command line text editors and change a specific users shell.
Change User Shell in Passwd File
When your done editing, save and close the file.
Do not forget to read these related topics:
In this article, we described various ways of changing a user’s shell in Linux. To share any thoughts with us, use the comment section below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Как определить и изменить командную оболочку (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, выполните команду
Источник
UNIX / Linux : What Is a Shell? What are different Shells?
What Is a Shell?
A shell is a program that provides an interface between a user and an operating system (OS) kernel. An OS starts a shell for each user when the user logs in or opens a terminal or console window.
A kernel is a program that:
- Controls all computer operations.
- Coordinates all executing utilities
- Ensures that executing utilities do not interfere with each other or consume all system resources.
- Schedules and manages all system processes.
By interfacing with a kernel, a shell provides a way for a user to execute utilities and programs.
User Environment
The shell also provides a user environment that you can customize using initialization files. These files contain settings for user environment characteristics, such as:
- Search paths for finding commands.
- Default permissions on new files.
- Values for variables that other programs use.
- Values that you can customize.
What are the different Shells?
The following sections describe OS shells mostly available on UNIX/Linux Operating system. Shell features and their default prompts are also described.
1. The Bourne Shell
The Bourne shell (sh), written by Steve Bourne at AT&T Bell Labs, is the original UNIX shell. It is the preferred shell for shell programming because of its compactness and speed. A Bourne shell drawback is that it lacks features for interactive use, such as the ability to recall previous commands (history). The Bourne shell also lacks built-in arithmetic and logical expression handling.
The Bourne shell is the Solaris OS default shell. It is the standard shell for Solaris system administration scripts. For the Bourne shell the:
- Command full-path name is /bin/sh and /sbin/sh.
- Non-root user default prompt is $.
- Root user default prompt is #.
2. The C Shell
The C shell (csh):
- Is a UNIX enhancement written by Bill Joy at the University of California at Berkeley.
- Incorporated features for interactive use, such as aliases and command history.
- Includes convenient programming features, such as built-in arithmetic and a C-like expression syntax.
For the C shell the:
- Command full-path name is /bin/csh.
- Non-root user default prompt is hostname %.
- Root user default prompt is hostname #.
3. The Korn Shell
The Korn shell (ksh):
- Was written by David Korn at AT&T Bell Labs
- Is a superset of the Bourne shell.
- Supports everything in the Bourne shell.
- Has interactive features comparable to those in the C shell.
- Includes convenient programming features like built-in arithmetic and C-like arrays, functions, and string-manipulation facilities.
- Is faster than the C shell.
- Runs scripts written for the Bourne shell.
For the Korn shell the:
- Command full-path name is /bin/ksh.
- Non-root user default prompt is $.
- Root user default prompt is #.
4. The GNU Bourne-Again Shell
The GNU Bourne-Again shell (bash):
- Is compatible to the Bourne shell.
- Incorporates useful features from the Korn and C shells.
- Has arrow keys that are automatically mapped for command recall and editing.
For the GNU Bourne-Again shell the:
- Command full-path name is /bin/bash.
- Default prompt for a non-root user is bash-x.xx$. (Where x.xx indicates the shell version number. For example, bash-3.50$)
- Root user default prompt is bash-x.xx#. (Where x.xx indicates the shell version number. For example, bash-3.50$#)
Here is a short comparison of the all 4 shells and their properties.
Источник