- Understanding Shell Initialization Files and User Profiles in Linux
- Shell Initialization in Linux
- 1. Interactive Login Shell
- 2. Interactive non-login Shell
- 3. Non-interactive Shell
- Understanding System-wide Shell Startup Files
- Understanding User-specific Shell Startup Files
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Startup scripts
- Contents
- Script Execution Order
- Usage
- How do I view dot (.) files?
- Власть над демонами или автозапуск в Linux
Understanding Shell Initialization Files and User Profiles in Linux
Linux is a multi-user, time sharing system, implying that more than one user can log in and use a system. And system administrators have the task of managing various aspects of how different users can operate a system in terms of installing/updating/removing software, programs they can run, files they can view/edit and so on.
Linux also allows users’ environments to be created or maintained in two major ways: using system-wide (global) and user-specific (personal) configurations. Normally, the basic method of working with a Linux system is the shell, and the shell creates an environment depending on certain files it reads during its initialization after a successful user login.
In this article, we will explain shell initialization files in relation to user profiles for local user management in Linux. We will let you know where to keep custom shell functions, aliases, variables as well as startup programs.
Important: For the purpose of this article, we will focus on bash, a sh compatible shell which is the most popular/used shell on Linux systems out there.
If you are using a different shell (zsh, ash, fish etc..) program, read through its documentation to find out more about some of the related files we will talk about here.
Shell Initialization in Linux
When the shell is invoked, there are certain initialization/startup files it reads which help to setup an environment for the shell itself and the system user; that is predefined (and customized) functions, variables, aliases and so on.
There are two categories of initialization files read by the shell:
- system-wide startup files – theses contain global configurations that apply to all users on the system, and are usually located in the /etc directory. They include: /etc/profiles and /etc/bashrc or /etc/bash.bashrc.
- user-specific startup files – these store configurations that apply to a single user on the system and are normally located in the users home directory as dot files. They can override the system-wide configurations. They include: .profiles, .bash_profile, .bashrc and .bash_login.
Again, the shell can be invoked in three possible modes:
1. Interactive Login Shell
The shell is invoked after a user successfully login into the system, using /bin/login, after reading credentials stored in the /etc/passwd file.
When the shell is started as an interactive login shell, it reads the /etc/profile and its user-specific equivalent
Linux Interactive Login Shell
2. Interactive non-login Shell
The shell is started at the command-line using a shell program for example $/bin/bash or $/bin/zsh. It can as well be started by running the /bin/su command.
Additionally, an interactive non-login shell can as well be invoked with a terminal program such as konsole, terminator or xterm from within a graphical environment.
When the shell is started in this state, it copies the environment of the parent shell, and reads the user-specific
/.bashrc file for additional startup configuration instructions.
Interactive Non-Login Shell
3. Non-interactive Shell
The shell is invoked when a shell script is running. In this mode, it’s processing a script (set of shell or generic system commands/functions) and doesn’t require user input between commands unless otherwise. It operates using the environment inherited from the parent shell.
Understanding System-wide Shell Startup Files
In this section, we will shade more light on shell startup files that store configurations for all users on the system and these include:
The /etc/profile file – it stores system-wide environment configurations and startup programs for login setup. All configurations that you want to apply to all system users’ environments should be added in this file.
For instance, you can set your the global PATH environment variable here.
System Wide Configuration File
Note: In certain systems like RHEL/CentOS 7, you’ll get such warnings as “It’s not recommended to change this file unless you know what you are doing. It’s much better to create a custom .sh shell script in /etc/profile.d/ to make custom changes to your environment, as this will prevent the need for merging in future updates”.
The /etc/profile.d/ directory – stores shell scripts used to make custom changes to your environment:
Stores Custom Shell Scripts
The /etc/bashrc or /etc/bash.bashrc file – contains system-wide functions and aliases including other configurations that apply to all system users.
If your system has multiple types of shells, it is a good idea to put bash-specific configurations in this file.
System Wide Functions and Aliases
Understanding User-specific Shell Startup Files
Next, we will explain more concerning user-specific shell (bash) startup dot files, that store configurations for a particular user on the system, they are located in a user’s home directory and they include:
User Specific Configuration Files
/.bash_profile file – this stores user specific environment and startup programs configurations. You can set your custom PATH environment variable here, as shown in the screenshot below:
User Bash Profile
/.bashrc file – this file stores user specific aliases and functions.
User Bashrc File
/.bash_login file – it contains specific configurations that are normally only executed when you log in to the system. When the
/.bash_profile is absent, this file will be read by bash.
/.profile file – this file is read in the absence of
/.bash_login; it can store the same configurations, which are can also be accessible by other shells on the system. Because we have mainly talked about bash here, take note that other shells might not understand the bash syntax.
Next, we will also explain two other important user specific files which are not necessarily bash initialization files:
/.bash_history file – bash maintains a history of commands that have been entered by a user on the system. This list of commands is kept in a user’s home directory in the
To view this list, type:
View Last Executed Commands
/.bash_logout file – it’s not used for shell startup, but stores user specific instructions for the logout procedure. It is read and executed when a user exits from an interactive login shell.
One practical example would by clearing the terminal window upon logout. This is important for remote connections, which will leave a clean window after closing them:
Clear History After Logout
For additional insights, checkout the contents of these shell initialization files on various Linux distros and also read through the bash man page:
That’s all for now! In this article, we explained shell startup/initialization files in Linux. Use the comment form below to write back to us.
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.
Источник
Startup scripts
If you’d like to set the bash environment variables permanently, add your settings to the initialization file located in the home directory of your account $HOME/.bash_profile.
Contents
Script Execution Order
- /etc/profile — It contains Linux system wide environment and startup programs. This file runs first when a user logs in to the system. This file also act as a system-wide profile file for the bash shell.
- /etc/profile.d — /etc/profile calls /etc/profile.d/. It is a directory and all scripts in this directory are called by /etc/profile using a for loop. This file runs second when a user logs in.
/.bash_profile is called in the users home directory ($HOME). This file runs third when a user logs in. This file calls
/.bashrc in the users home directory.
Please note that each script can add or undo changes made in previously called script. For example, the PS1 variable is set in the /etc/profile, but it can be modified in the
Usage
- Use above files to customize your environment.
- Typical examples:
- Set PATH and PS1 (shell prompt) variables.
- Set default printer via PRINTER variable.
- Set default text editor via EDITOR variable.
- Set default pager via PAGER variable.
- Set default umask (file mode creation mask).
- Override and remove unwanted settings such as variables or aliases (undo changes).
- Set up environment.
- Set up aliases.
- Set up functions.
How do I view dot (.) files?
Type the following command in your $HOME directory:
Источник
Власть над демонами или автозапуск в Linux
Для реализации автозапуска в Linux написано уже немало и на разных языках, но приходится искать, потому постарался свести большую часть тут. Здесь не рассказывается полностью весь процесс с нуля, но предоставлено достаточно информации и ссылок, чтобы сделать атоматический запуск программ в Linux реальностью.
Стоит сразу заметить — чтобы программа была полноценным сервисом/демоном, она должна быть соответствующе написана (link1, link2). Впрочем такое делают не всегда, хотя возможно это и не совсем правильно.
Существуют несколько способов сделать автозапуск программ в Linux:
- записать вызов программы/скрипта запуска в /etc/rc.local в фоновом режиме (&) (в разных дистрибутивах может лежать в разных местах, например, /etc/rc.d/rc.local) с перенаправленными потоками ввода/вывода в /dev/null. Например, «/home/user/my_prog 1 > /dev/null 2 > /dev/null &». Также, дополнительно, можно воспользоваться командой nohup;
- внести вызов в /etc/inittab, согласно правилам его оформления. В отличие от первого способа тут можно указать уровень запуска для программы;
- написать скрипт, позволяющий запускать/останавливать/перезапускать программу как демона, а также получать информацию о её состоянии.
Первый способ самый лёгкий, но и самый проблемный. Файл rc.local есть не во всех дистрибутивах. В нём нельзя задать уровень запуска. Если там записано несколько программ, то сложно ими управлять как сервисами (разве что запустить или остановить все одновременно). И, под конец, запуск из него подрывает устойчивость системы от взлома (примеры можно легко найти в поисковике).
Второй метод довольно экзотичный, сам узнал о нём совсем недавно, хотя пишут, что им пользуются многие администраторы. Тем не менее, используя его, нельзя оперировать запущенными таким способом программами как демонами, что довольно неудобно. Да и загромождать inittab некрасиво.
Последний метод на текущий момент самый «кошерный», но немного сложнее предыдущих (возможно, на первый взгляд). Именно им представлены все системные демоны, что говорит само за себя. Потому его и рассмотрю ниже.
Также есть способ автозапуска графических программ, но его опишу в конце, отдельно от остальных, т.к. он имеет недемоническую сущность.
Сразу обмолвлюсь, что у меня стоит Debian 6 и в других дистрибутивах пути могут несколько различаться.
Автозапуск программы как демона
Обычно в системе уже есть много подсказок как это сделать, но всё-таки приходится лазить по разным файлам и искать в интеренете дополнительную информацию. Это не значит, что я опишу тут каждую букву, но искать придётся меньше, надеюсь.
Для начала стоит заглянуть в каталог /etc/init.d. Здесь содержатся запускные скрипты всех сервисов, а также два файла для желающих написать себе такой же:
README и skeleton
skeleton содержит в себе болванку скрипта запуска с довольно подробными комментариями, а README его неплохо дополняет, не смотря на его небольшой размер. Также можно посмотреть и другие файлы и попытаться найти там что-то, что прояснит непонятную ситуацию.
В 6-ом debian`е для запускных скриптов демонов используется LSB (Linux Script Base) Init Standart. Почитать о нём подробнее можно тут. Для систем, где LSB не используется стоит взглянуть сюда.
Рассмотрим поближе файл skeleton. Первое с чего он должен начинаться, конечно же «#!/bin/sh», т.к. init-скрипт — запускной файл. Далее идёт комментированный заголовок:
Может показаться, что это просто лишняя информация от автора, но это не так. То, что указано здесь используется при прописывании скрипта в систему. Тут как раз пригодится файл README, который показывает, что в заголовке skeleton перечислены не все возможные параметры. Как минимум есть ещё следующие:
Все параметры и их полное описание (на английском) можно увидеть тут, а на русском тут и тут (спасибо awzrno за новые ссылки ^_^). К русскому варианту добавлю, что в Required-Start: можно прописать $all, тогда текущий скрипт будет запускаться после всех остальных (иногда это бывает нужно). Также X-Interactive: true показывает, что этот скрипт может взаимодействовать с пользователем, запросом на ввод чего-нибудь, например пароля.
Далее в skeleton идёт инициализация переменных, используемых в самом скрипте. Часть из них нужно будет настроить под свои нужды. Потом проверки на то, что сам демон существует и попытка прочитать конфигурационный файл (их имена должны быть указаны в переменных выше), далее загрузка переменных rcS, а потом идёт одна из самых интересных частей init-файла:
. /lib/lsb/init-functions
это определение LSB функций работы с логами, LSB-статусом сервиса, работы с процессом. В некоторых дистрибутивах этот файл может находиться в каталоге /etc/init.d. Названия и часть подробностей можно узнать непосредственно из комментариев к функциям в этом файле, а также тут.
Следующая часть — непосредственно тело скрипта. Тело состоит из условных частей, которые являются командами для демона: start, stop, restart/reload/force-reload, status. Кто-то выделяет их в отдельные функции, кто-то нет. На мой взгляд, функциями они выглядят эстетичнее и код более понятен. Все эти команды объединяет оператор выбора case, который и выбирает для исполнения нужный кусок кода, в зависимости от команды (параметра) с которой был запущен init-скрипт.
Таким образом для создания обычного скрипта достаточно подставить в переменные в начале файла нужные значения и, возможно, немного добавить кода в функции start/stop (например загрузку/выгрузку драйвера).
После того как файл будет готов его нужно скопировать в /etc/init.d и добавить в автозагрузку:
update-rc.d defaults
(или insserv для debian 6 stable и выше)
Удалить из автозагрузки можно так:
update-rc.d -f remove
(или insserv -r для debian 6 stable и выше)
Далее также можно использовать команды sysv-rc-conf в debian или service в fedora core, чтобы включить/выключить автозагрузку сервиса.
Автозапуск графического ПО без ввода паролей
Сама по себе реализация такой возможности понижает уровень защищённости ОС, т.к. войти может любой. Но бывают ситуации, когда это необходимо. Рассмотрю тут варианты только для двух основных графических менеджеров, т.к. других установленных под рукой нет.
Убрать запрос пароля на вход можно в центре управления (kcontrol) -> системное администрирование -> менеджер входа в систему -> удобства. Там выбрать пользователя, под которым входить (кроме рута) и поставить нужные галочки (разрешить автовход и вход без ввода пароля).
Чтобы сделать автозапуск программы нужно в каталог /home/ /.kde/Autostart добавить ссылку на запускной файл/скрипт нужного ПО.
Тут убрать запрос пароля на вход можно также в центре управления (gnome-control-center) -> Login Screen. Там, под рутом (ткнуть на замок, ввести пароль) выбрать пользователя, под которым входить (кроме суперпользователя).
Для автозапуска программы опять же в центре управления выбрать Startup Applications -> Add и заполнить маленькую форму.
Для обоих графических менеджеров:
Если нужно запустить под обычным пользователем, но от рута, то ещё надо настроить правила в /etc/sudoers на запуск конкретной программы/набора программ от имени суперпользователя (манами рекомендуется для безопасности делать это с помощью visudo). Как это делать рассказывать не буду, т.к. в man sudoers всё хорошо расписано.
Источник