Linux user login shell

What are login and non-login shells?

It is said that settings for non login shell to go into .bashrc file and login shell settings to go into .profile file. What is really meant by login and non-login shells? Please explain without using technical jargon as far as possible.

2 Answers 2

Simply put:

  • If you open a shell or terminal (or switch to one), and it asks you to log in (Username? Password?) before it gives you a prompt, it’s a login shell.
  • If it doesn’t (like gnome-terminal), and lets you use it straight away, it’s a non-login shell.

If you are a normal user of Ubuntu Desktop, the only login shell is. your desktop (you type a password to get in, right ;)? Well, technically it’s a login shell that starts a GUI, but that’s getting in to jargon. And yes, it will read the settings in .profile

The only time you (a normal user) will probably see a login shell that looks like a login shell is if you are having some problem with your desktop and you switch to a virtual terminal with the Ctrl + Alt + F1 shortcut.

The other general cases for having a login shell include:

  • accessing your computer remotely via ssh (or connecting locally with ssh localhost )
  • simulating an initial login shell with bash -l (or sh -l )
  • simulating an initial root login shell with sudo -i
    • or sudo -u username -i for another non- root user

    If I start my Eclipse IDE from terminal, it opens as expected, but if I try to open it by clicking the Eclipse icon, it is unable to recognize Java location (unless otherwise PATH for Java is set in .profile file). That means clicking Eclipse icon needs a login shell, why?

    @DUKE, No, it means that environment variables need to be set differently when you are using a desktop/GUI versus a true command-line-only console system. Put your PATH, etc. in ~/.pam_environment (variables only, no bash commands in there!), logout, login, and watch everything magically appear in the desktop as well as in gnome-terminal!

    Login via ssh does not invoke a login shell. It doesn’t load /etc/profile , /etc/profile.d or ~/.profile .

    @xuhdev Login via ssh does invoke a login shell and it does load /etc/profile, /etc/profile.d and ~/.bash_profile.

    I do not think that correct answer can be given without “technical jargon”. Since this question is the first one popping up in Google for the query “what is a login shell” I am providing a more correct answer below:

    Login shell is simply a shell that was told to be a login shell. It does not mean shell that pops up after you login, though usually application that logs you in is telling shell it launches to be a login shell. There exists the following ways to tell shell it should be a login one:

    1. Running shell with -l or —login argument assuming it knows it (I do not know any shells which do not know -l , but —login is only supported by a few shells).
    2. Running shell with argv[0] set to — (i.e. with HYPHEN-MINUS prepended to usual argv[0] or to some other string). This is what ssh and su do: su just runs executable with -su as argv[0] (hello to everybody thinking argv[0] has something to do with currently running executable name), ssh runs zsh with -zsh when user has set /bin/zsh as his shell.

    Loginess of the shell has absolutely nothing to do with anybody asking you a password or performing some other authenication procedure. Some programs like ssh or login (or some terminal emulators like urxvt) run shells as a login ones using argv[0] that starts with a HYPHEN-MINUS. Some like su or sudo (or zsh: see — precommand modifier described in section PRECOMMAND MODIFIERS in man zshmisc ) do not do this by default, but can be told so. Some have the only option of telling shell to be the login one using its argument (i.e. bash -l ): ssh with a command argument (that explicitly tells ssh what to run on the remote end).

    Generally it is better to first consult the documentation of the program used to invoke the shell to determine whether shell will be the login one and second perform some tests to determine whether app will launch a login shell (e.g. by adding echo to .profile ).

    Источник

    Различия между Login shell и Non login shell (оболочка с входом и оболочка без входа)

    В документации по Linux можно встретить термины Login shell и Non login shell. Понятно, что оба они относятся к оболочке, причём первый связан с входом пользователя в систему, а второй не связан с входом пользователя. По большому счёту название уже отражает их ключевые различия.

    Далее мы узнаем чем различаются Login shell и Non login shell с технической точки зрения.

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

    Ключевое различие между Login shell и Non login shell заключается в настройке автозапуска этих скриптов.

    1) Login shell (оболочка с входом)

    Login shell (оболочка с входом) при запуске предлагает пользователю выполнить вход, после успешного входа пользователя продолжает работу используя /bin/login и считывая данные из файла /etc/passwd. Login shell — это первый процесс, который выполняется от ID нашего пользователя когда вы ходим в сессию. Этот процесс входа говорит оболочке вести себя как login shell и следовать конвенции: передать аргумент 0, который обычно является именем исполнимого файла оболочки, перед которым поставлен символ «». Например, для оболочки Bash это будет -bash.

    Когда вызывается Bash в качестве Login shell (оболочки входа), то происходит следующее:

    →Процесс входа вызывает /etc/profile

    /etc/profile вызывает скрипты в /etc/profile.d/

    →Процесс входа вызывает ~/.bash_profile

    ~/.bash_profile вызывает ~/.bashrc

    ~/.bashrc вызывает /etc/bashrc

    Login shells включают в себя следующие случаи.

    • Оболочки создаются с явным указанием на вход. Примеры:

    su - su -l su --login su USERNAME - su -l USERNAME su --login USERNAME sudo -i

    • Оболочка создаётся при входе, включая X (графический) вход.

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

    Если в выводе будем имя оболочки, перед которой стоит тире, то значит это login shell. Примеры: -bash, -su и т.д.

    2) Non login shell (оболочки без входа)

    Оболочки без входа запускаются программами без необходимости выполнять вход. В этом случае программа просто передаёт имя исполнимого файла оболочки. Например, для оболочки Bash это будет просто bash.

    Когда bash вызывается как Non login shell (оболочки без входа), то происходит следующее:

    →Процесс без входа (оболочка) вызывает ~/.bashrc

    ~/.bashrc вызывает /etc/bashrc

    /etc/bashrc вызывает скрипты в /etc/profile.d/

    Non login shells включают в себя следующие случаи.

    • Оболочки создаются с использованием показанного ниже синтаксиса команд. Например:

    • Любые другие экземпляры bash

    Non login shell (оболочка без входа) может быть распознана по следующей процедуре. Выполните приведённую ниже команду:

    Если вывод — это имя нашей оболочки перед которым не стоит дефис, значит это оболочка без входа. Например, это могут быть bash, su и т.д.

    Вывод

    Итак, если вы вводите учётные данные для входа, то значит перед вами Login shell. На настольных системах в оболочке входа запускается графическая система. Все последующие открываемые консоли являются Non login shell. Попасть в Login shell можно переключившись по CTRL+ALT+F*, либо подключившись по SSH, либо выполнив одну из приведённых выше команд.

    Кроме различия в необходимости ввода логина и пароля, также в Login shell и Non login shell различные наборы скриптов, которые выполняются при открытии этих видов оболочек.

    Источники:

    Источник

    Interactive, Non-interactive, Login, Non-login Shells in Linux

    announcement - icon

    The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

    To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

    Connect your cluster and start monitoring your K8s costs right away:

    1. Overview

    The shell is a command line interpreter in Linux. It’s a program that receives commands from the user and gives them to the operating system to execute. Further, bash is the default login shell for most Linux distributions, but there are other Linux shells like the Korn shell (ksh), the Z shell (zsh), and the C shell (csh).

    In this tutorial, we’ll learn the difference between interactive, non-interactive, login, and non-login shells.

    2. Interactive Login Shell

    An interactive shell receives commands from the user and displays output to the user. Moreover, users get a login shell when they login to their account.

    We get an interactive login shell when we use programs like ssh or telnet:

    $ ssh localhost $ echo $- himBHs $ shopt login_shell login_shell on
    • $- is a special bash parameter that returns the option flags used in the current bash shell. Further, if it includes i, it means that the shell is interactive
    • shopt login_shell tells us if the login_shell shell option is set

    Thus, we have an interactive login shell.

    3. Interactive Non-login Shell

    We get an interactive non-login shell when we open up a terminal on our Linux machine:

    $ echo $- himBHs $ shopt login_shell login_shell off

    We can see that we got an interactive, non-login shell.

    4. Non-interactive Login Shell

    If we give something other than tty (for example, a command) as stdin to ssh, we receive a non-interactive login shell:

    $ echo 'echo $-; shopt login_shell' | ssh localhost Pseudo-terminal will not be allocated because stdin is not a terminal. hBs login_shell on

    In the above snippet, we passed ‘echo $-; shopt login_shell’ as stdin to ssh. As a result, we got a non-interactive login shell.

    5. Non-interactive Non-login Shell

    Finally, we get a non-interactive non-login shell when we run a script on our machine. That is because they run in their new shell that is non-interactive:

    $ echo 'echo $-; shopt login_shell' > script.sh $ chmod +x script.sh $ ./script.sh hBH login_shell off

    To clarify, we wrote ‘echo $-; shopt login_shell’ into script.sh and then made it executable using chmod. After that, we ran the script.

    As we can see, we got a non-interactive non-login shell.

    6. Conclusion

    In this article, we learned about the different kinds of shells we can get in the Linux environment.

    Источник

    Читайте также:  What is package installation in linux
Оцените статью
Adblock
detector