File etc profile linux

Understanding user profile files in Linux — .bashrc, .bash_profile, /etc/profile, /etc/bashrc

Individual users have personal habits and preferences for their Linux work environment, and so a variety of profile file configurations are available to help them customize their experience. These customizations are referred to as profiles. An initial profile is created when the user account is created. There are many files and directories from which information is initially pulled to create a standard profile.

.bashrc file

The .bashrc file enables customization of the user’s own environment. The file is stored in a user’s home directory. Because the .bashrc file is unique to each user, it can be configured to a user’s own specific needs or preferences.

A good example of the use of the .bashrc file is the use of aliases. Users can specify their own abbreviated commands without impacting the experience of any other user on the system. Another common configuration within .bashrc is environment variables. Users can also use the file to customize the command prompt to provide the information they want.

Example Configurations

Other than creating aliases, the .bashrc file is often configured to set the default directory and file permissions for the user. Also, the default command prompt can be altered to provide more information. Most distributions place the user name, system hostname, and current directory in the prompt, but that can be changed.

bashrc file example in Linux

.bash_profile file

The .bash_profile file provides shell configuration for the initial login environment. This differs from the .bashrc file, which provides settings for all of the user’s interactive shells. The .bash_profile file is only read with the first login, while the .bashrc is read with all subsequent logins.

A default .bash_profile can be provided to new users via the /etc/skel directory.

bash_profile example in Linux

Global User Profiles

An administrator may find it desirable to define system-wide settings or to configure initial settings for users. The files and directories that follow give the administrator the flexibility to make a variety of configurations, which may be later customized by a user for their own specific needs.

The /etc/skel/ Directory

The contents of the /etc/skel/ directory are automatically copied into the home directories of new users. Administrators can pre-populate the /etc/skel/ directory with configuration files or other content. When the useradd command is run, the /etc/skel/ directory’s contents are copied to the new user’s home directory, immediately giving them the configurations they might need.

Читайте также:  Creating user in linux command

Note that files added to the /etc/skel/ directory after a user account is created will not be copied to the home directories of existing users.

/etc/profile file

The /etc/profile file provides system-wide environment variables. This may be more effective for administrators to configure if there are settings that apply to all users.

During the initial login process for a user, the system reads the /etc/profile file first for Bash shell configurations, and then any user-specific Bash customizations are pulled from the .profile file located in the user’s home directory. The .profile file runs each time a new shell is started, whereas /etc/profile is only run at login. This approach enables administrators to define global shell settings, but still allow user-specific customizations.

Example

An example of a .profile is as follows:

PATH=$PATH:$HOME/bin:/scripts MAIL=/var/mail/$LOGNAME EDITOR=emacs export PATH MAIL EDITOR 

The first line defines the paths of executable files; the second line defines the path for where incoming email messages are stored; and the third line defines the default text editor. The last line actually ensures these variables are implemented in the environment.

/etc/profile.d/ Directory

The /etc/profile.d/ directory serves as a storage location for scripts administrators may use to set additional system-wide variables. It is recommended you set the environment variables via scripts contained in /etc/profile.d/ rather than editing the /etc/profile file directly.

/etc/bashrc File

The /etc/bashrc file provides system-wide Bash settings. This is a little different than /etc/profile, which is used for variables.

Источник

Профили пользователя Bash

img

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

  1. Установка переменных во время входа в систему или при запуске оболочки.
  2. Написание bash-сценариев для часто используемых цепочек команд.
  3. Управление структурой каталогов для новых пользователей.
  4. Настройка корректных путей поиска команд.

Командная оболочка в Unix системах называется Shell – это командный интерпретатор, который используется во всех Unix подобных операционных системах. Оболочек огромное количество. Одной из основных оболочек является оболочка BASH или Bourne-again-shell (Еще одна оболочка Борна). Данная оболочка самая распространенная оболочка Unix, которая используется по умолчанию практически во всех дистрибутивах Linux. Все, о чем будет написано далее справедливо для большинства дистрибутивов Linux. Есть небольшой нюанс с Ubuntu.

Профили

Есть вот такая картинка по профилям. Значок ~ в данном случае означает домашнюю папку пользователя по умолчанию. Например, /home/john .

Существует папка /etc/profile в ней лежат настройки глобального профиля. Такой профиль, который будет применяться для всех пользователей на данной машине, которые запускают командную оболочку. Функционал у него достаточно большой, но в первую очередь он грузит все что есть в /etc/profile.d и настройки глобального пользователя /etc/bash.bashrc и /etc/bashrc . Получается так, что ищется файл bash.bashrc или bashrc файлы, т.к в разных дистрибутивах разные файлы и грузит то, что он нашел. В документации по Linux написано, если запускается инициализационный скрипт при входе в систему, т.е пользователь заходит в систему, то отрабатывает левая часть картинки, если запускается оболочка вне контекста пользователя, то правая часть.

Читайте также:  Kali linux odroid c2

Если пользователь залогинился в систему, то помимо того, что отрабатывает папка /etc/profile.d начинается проверка в домашнем каталоге пользователя наличие файлов ~/.bash_profile , ~/.bash_login , ~/.profile . В разных дистрибутивах по-разному называется локальный профиль пользователя. В Ubuntu файл ~/.profile просто ссылит на ~/.bashrc , который так же лежит в домашней папке пользователя. Т.е у нас по порядку инициализационный скрипт ищет, как указанно в левой части картинки. Точкой у Ubuntu обозначаются скрытые файлы.

Вот этот файл ~/.bashrc – это настройки конкретного пользователя, настройки оболочки. Файл /etc/bashrc – это настройки глобального пользователя, настройки для всех пользователей.

Суть процесса: оболочка bash используется, как интерактивная оболочка входа в систему. Данная оболочка вызывает команды из файла /etc/profile , если он существует. Далее она по порядку начинает обрабатывать файлы ~/.bash_profile , ~/.bash_login , ~/.profile . И еще есть такой файл в home директории ~/.bash_logout – он отрабатывает при выходе из системы, что следует из его названия.

Есть второй сценарий, использование интерактивной оболочки bash, без входа в систему, то читаются файлы /etc/bash.bashrc и /etc/bashrc .

Мы можем посмотреть, что происходит при запуске оболочки. Для начала найдем файл /etc/profile .

/etc/profile

Из картинки мы видим, что данный файл грузит /etc/bash.bashrc , в некоторых дистрибутивах это просто /etc/bashrc . И затем он выполняет из папки /etc/profile.d/*.sh , т.е все скрипты. Об этом можно прочитать в комментарии, всего два действия.

Посмотрим файл cat /etc/bash.bashrc .

cat /etc/bash.bashrc

Данный файл определяет поведение командной строки, он определяет глобальный профиль пользователей. Все, что в нем указанно справедливо для всех пользователей. Данный файл запускает различные псевдонимы и глобальные функции, различные настройки.

В каталоге /etc , есть папка profile.d , в ней могут находиться различные скрипты и они будут запускаться.

profile.d

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

cd ~

Смотрим очередность запуска файлов и видим, что следующий файл, который запустится, будет ~/.profile . он содержит настройки конкретного пользователя. Посмотрим, что в нем есть cat ~/.profile .

Читайте также:  Как начать установку linux

cat ~/.profile

В нем несколько переменных и он ссылит на файл ~/.bashrc . Это особенность Ubuntu. И в файле ~/.bashrc хранятся все настройки.

~/.bashrc

Он достаточно большой. В нем пишутся настройки истории, как происходит обновление, псевдонимы, цветовые настройки.

Можно посмотреть файл ~/.bash_logout .

~/.bash_logout

В данном файле нет ничего особенного, просто, когда кто-то выходит экран в целях безопасности очищается.

Посмотрим, как создается структура каталогов для новых пользователей. Есть такая папка в /etc/skel/ . Если мы туда перейдем и посмотрим, что в ней находиться.

/etc/skel/

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

Источник

Understanding /etc/profile Configuration File in Linux

The /etc/profile file provides system-wide environment variables. This may be more effective for administrators to configure if there are settings that apply to all users.

During the initial login process for a user, the system reads the /etc/profile file first for Bash shell configurations, and then any user-specific Bash customizations are pulled from the .profile file located in the user’s home directory. The .profile file runs each time a new shell is started, whereas /etc/profile is only run at login. This approach enables administrators to define global shell settings, but still allow user-specific customizations.

Note: The global file is /etc/profile (without the “dot” as the first character of the file name), while the user-specific file is .profile, indicating that the file is hidden.

The profile file located in /etc is read automatically by everyone when they log in. This file will generally contain:

  • global or local environment variables
  • PATH information
  • terminal settings
  • security commands
  • message of the day or disclaimer information

An example of a .profile is as follows:

# cat /etc/profile PATH=$PATH:$HOME/bin:/scripts MAIL=/var/mail/$LOGNAME EDITOR=emacs export PATH MAIL EDITOR

The first line defines the paths of executable files; the second line defines the path for where incoming email messages are stored; and the third line defines the default text editor. The last line actually ensures these variables are implemented in the environment.

The /etc/profile.d/ Directory

The /etc/profile.d/ directory serves as a storage location for scripts administrators may use to set additional system-wide variables. It is recommended you set the environment variables via scripts contained in /etc/profile.d/ rather than editing the /etc/profile file directly.

Источник

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