What is bashrc in linux

What is bashrc in linux

Недавно я столкнулся со следующей проблемой: приложение не сохраняло настройку umask , заданную в профиле root-пользователя, или в файле /etc/profile . Немного разобравшись в вопросе, я понял, что приложение использует только ту настройку umask , которая задана в /etc/bashrc , не принимая даже те значения, которые являются его же собственными сценариями запуска.

Немного изучив вопрос, я понял, какую функцию выполняют эти файлы, чем они различаются и как они выполняются. Такой вопрос поднимается не часто, поэтому я подумал, что будет полезно рассказать о нем вам.

Для чего нужен файл /etc/profile?

Если вы используете Linux, то вам наверняка знакомы файлы .profile или .bash_profile , размещенные в вашем домашнем каталоге. Эти файлы используются для задания элементов окружения для оболочки пользователя. Таких элементов, как, например, umask , и таких переменных, как PS1 или PATH .

Файл /etc/profile не очень-то отличается от этих файлов. Он используется для задания общесистемных переменных окружения в оболочках пользователя. Иногда это те же переменные, что и в .bash_profile , но этот файл используется для задания первоначальных PATH или PS1 для всех пользователей оболочек системы.

/etc/profile.d

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

Для чего нужен файл /etc/bashrc?

Помимо .bash_profile , в своем домашнем каталоге вы также часто будете встречать файл .bashrc . Этот файл предназначен для задания псевдонимов команд и функций, используемых пользователями оболочки bash.

Аналогично тому, как /etc/profile является общесистемной версией .bash_profile , файл /etc/bashrc в Red Hat и файл /etc/bash.bashrc в Ubuntu являются общесистемной версией .bashrc .

Стоит отметить, что в Red Hat реализация /etc/bashrc также выполняет сценариий оболочки в /etc/profile.d , но только если пользовательская оболочка является Интерактивной оболочкой (т.е. Login Shell (стартовой оболочкой))

Когда используются эти файлы?

То, когда выполняется каждый из этих файлов, зависит от типа выполняемого логина. В Linux имеется два типа стартовых оболочек (login shells) — Интерактивные оболочки и Неинтерактивные оболочки. Интерактивная оболочка используется, когда пользователь может взаимодействовать с оболочкой, т.е., например, типичное приглашение командной строки bash. Неинтерактивная оболочка используется, когда пользователь не может взаимодействовать с оболочкой, т.е. выполнение bash-сценариев.

Разница проста: файл /etc/profile выполняется только для интерактивных оболочек, а файл /etc/bashrc – как для интерактивных, так и для неинтерактивных. Вообще-то, в Ubuntu файл /etc/profile вызывает файл /etc/bashrc напрямую.

Интерактивная оболочка и неинтерактивная оболочка: Сравнение

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

/etc/profile

/etc/bash.bashrc

Интерактивная оболочка

Ниже приведен пример интерактивной оболочки. В этом случае были выполнены оба файла /etc/profile и /etc/bash.bashrc .

Неинтерактивная оболочка

В этом примере мы выполняем команду через оболочку SSH, которая является неинтерактивной; поскольку это неинтерактивная оболочка, выполняется только файл /etc/bash.bashrc .

Заключение

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

Источник

What is Linux bashrc and How to Use It? [Full Guide]

Updated on September 9, 2020

Are you a user of Linux and want to work with Linux bashrc and its command-line? bashrc is one of the hidden files in the home directory of the Linux operating system but how about bash_profile? Do you know what is the differences between Linux bashrc and bash_profile? By default, Linux hides the sensitive files. One of them is bashrc, which is located in the home directory of the Linux operating system.

Читайте также:  Windows sp2 and sp3

As you probably know, bashrc is a low-risk and straightforward solution in comparison to other terminal customization tricks (if you face a problem, delete bashrc and start it again). In this article, we will explain the introduction of bash in Linux. We will also tell you what .bashrc files are and how to use them. Nevertheless, before anything, let us start explaining with some basic definitions.

What is A Shell?

A shell is a term used for interacting user interface with OS. A shell is a command interpreter (in some systems) that accepts the user’s commands and runs them to execute operations. In fact, a Linux/Unix shell is an environment for running scripts, commands, or programs. There are two major kinds of shells:

  • C Shell – if you are using this type of shell, the % character is the default prompt.
  • Bourne Shell – the main prompt for this kind of shell is $ character.

In this article, we will use Bourne Shell. This kind of shell has the following subcategories:

  • Bourne Shell (sh)
  • Bourne Again Shell (bash)
  • Korn Shell (KSH)
  • POSIX Shell (sh)

Since Bourne Shell was the first shell that appeared to UNIX, it was referred to as the shell. As was mentioned, bash is the most common type of shell for Linux and is suitable for writing scripts on different versions of Linux.

Get yourself an economy or premium Linux VPS for hosting your website or remote desktop, at the cheapest price out there. VPS Running on Linux KVM for increased efficiency and working on powerful hardware with NVMe SSD storage for increased speed.

What is Bashrc File and How to Use It?

.bashrc File will execute when a user opens a new shell in an interactive mode. In fact, the .bashrc File is a shell script to initialize a shell session. You can put all commands in this file (those commands you can type in the command prompt). Every time you need to initiate the .bashrc File from the beginning, you can start it by pressing Ctrl+Alt+T; or do it by opening a new terminal tab. At each launch, Bash runs the contents of the .bashrc file to load your preferences. You can find this shell script in the home directory of users. The main function of this file is loading the terminal preferences and environmental variables and saving them.

Therefore, the first step of the bashrc command using (Ctrl+Alt+T) is opening a new terminal window and the result of that is returning the following files:

  1. /etc/skel/.bashrc When new users create in the system, /etc/skel/.bashrc is the default bashrc file for each user.
  2. /home/Ali/.bashrc When a user named Ali opens the shell, this file is in use.
  3. /root/.bashrc Whenever the root opens the shell, the root file ( /root/.bashrc ) will utilize.

Where Is Bashrc File in Linux?

As we mentioned, the location of bashrc is in your home directory. When a bash shell or a bash script is initiated, it will read and execute. In fact, reading the bashrc file will take place in one of the following sample situations:

  • When you log in,
  • When you run certain commands (bash scripts),
  • When copying error files or output,
  • When you run compute jobs,
  • At the end of a job.

What Can You Do With Linux Bashrc?

Providing a space for setting up the variables, aliases, functions, and define other settings is the main purpose of a bashrc Files. Moreover, it has very noticeable advantages that you can utilize to make your terminal experience more user-friendly and efficient. We will explore some of them here.

Bash Prompts

A customizable bash prompt reads a configuration file to determine its behavior. It makes your work on the terminal more efficient and productive. Bash prompt allows you to personalize your terminal. It also lets you show prompts when you run a command. For example, you can perform the following tasks:

Читайте также:  Иконки сталкер для windows

1. Change the Color on bash Command

If you wish to change the color of your shell prompt, type the following export command:

This will set a red color for your prompt (0;31 is the code of red).

2. Multiline Prompt

You know, bash does not support multiline comments. However, sometimes you need to continue your commands without having to finish them. In this situation, you have to use an open quote (‘or “), backslash (\), or pipe symbol ( | ) at the end of each line to continue your commands and stop them from executing.

A multi-line prompt will contain user and host, date/time, active terminal, full path, space usage, and even file count. In multiline prompts, you will get a secondary prompt from PS2 that is set to >, by default.

3. Display Directory Information

If you intend to display the user/host, a number of tasks, and date on the top line, this prompt will work. In addition, it will present the number of files in the current directory and their disk usage. Its code will be something like this:

4. High-Performance Simple Prompt

5. The Rob Prompt

Although rob code is small and simple, it allows the features that appear in considerable examples and more complex manner

Note: to make use of any of these prompts, you can copy & paste the “PS1=” line directly into your terminal. If you wish to make permanent changes, paste the line to the end of your

Creating Aliases

Creating aliases for your most-used commands will save you some time. Aliases are like custom shortcuts used to represent a command (or set of commands) executed with or without custom options. For example, the command “ls”. This command is a worthwhile command that can display the contents of your directory. You know, knowing the hidden contents of the Directory or having information about the Directory will be more profitable. Therefore, we use an alias here.

Get yourself an economy or premium Linux VPS for hosting your website or remote desktop, at the cheapest price out there. VPS Running on Linux KVM for increased efficiency and working on powerful hardware with NVMe SSD storage for increased speed.

One of the most frequently used aliases is ll which will be set to run “ls –lha” or something similar. That will display the most details about files, revealing hidden files, and show file sizes in units that are readable to us. You can also utilize this command for creating shorter versions of codes or forcing a code to always run with your favored flags, or even guard against common typos. You can also circumvent annoying or easy-to-forget syntax with your preferred shorthand. A list of defined aliases on your profile will display by simply executing the alias command:

The output of this command will display the default aliases defined for your user in Ubuntu 18.04 as shown in the following picture:

As you can see, $ ll Is equivalent to running $ ls –alF. You can also create your temporary aliases. To do so, Type the alias word. Then, use the name you wish to use for executing a command that is followed by the = sign and quote the command you want to alias. The syntax is something like this:

You can then use this shortcut to go to the webroot directory. However, it has one problem. This is only available for your current terminal session, and if you open a new terminal session, the Alias will no longer be available. So, if you wish to save your Aliases, you require a permanent Alias.

Get yourself an economy or premium Linux VPS for hosting your website or remote desktop, at the cheapest price out there. VPS Running on Linux KVM for increased efficiency and working on powerful hardware with NVMe SSD storage for increased speed.

Читайте также:  Как восстановить забытую сеть wifi windows

How to Open Bashrc and Save a File?

The syntax you should use is practically the same as creating a temporary alias, except this time, you also have to save it in a file. So:

Step 1: Open a .bashrc file in a sample bash like the following:

Step 2: Find a place in the file where you intend to keep the Aliases. For instance, you may want to add them at the end of the file.

Step 3: Save the file. This file will automatically load in your next session.

Note: the unalias command will use for removing an alias.

How to Edit .bashrc files

You may want to add your own commands in any terminal text editor. To do so, you can edit bashrc. We will use a nano editor in the following examples.

Step 1: To edit bashrc through nano, type the following command in Terminal:

Note: If it is the first time you are editing your .bashrc file, you might find that it is empty. That is not a problem. If not so, you can feel free to put your additions on any line.

Bring in your mind that next time you launch the terminal, any changes you make to .bashrc will apply. If you want to make use of them immediately, run the command below:

Step 2: Wherever you wish, you can add to your .bashrc file. Nevertheless, it is better to use a command (proceeded by #) for organizing your code.

Note: Bring in your mind that edits in .bashrc have to follow bash’s scripting format. If you do not know how to script with bash command, then, use online resources for that.

How to Reload bashrc File

If you intend to reload the bashrc file without opening a new file, run the following command:

As you know, the dot operator will execute this command from the file in the current environment. You can also use the source command as shown below:

What is bash_profile?

Every time you create a new bash session, a file for the bash profile will create. This is a file named .bash_profile in the home directory of your computer that bash runs. To create your bash file, run the following command:

) is equivalent to /User/Rich and tells bash to start traversing the file system from the home directory. It means, you can write the previous command in the following format:

But utilizing the (

) is a shortcut that is useable for every user to understand.

Where is bash_profile?

You may ask where the bash_profile path is. bash_profile is a hidden file located in the home folder, and you have to make it visible. If

/ .bash_profile does not exist,

/ .profile is located instead.

Bashrc vs. bash_profile

.bashrc is only sourced in interactive mode when bash does not act as a login shell. On the contrary, .bash_profile is only sourced as a non-interactive shell with the – login option, or when bash started as an interactive login shell. It means, it is suitable for commands that should run once while bashrc is great for commands that you should run in every new shell starting.

Get yourself an economy or premium Linux VPS for hosting your website or remote desktop, at the cheapest price out there. VPS Running on Linux KVM for increased efficiency and working on powerful hardware with NVMe SSD storage for increased speed.

Conclusion

We tried to give you a full hand in using Linux Bashrc. Of course, there is more to know about this topic but with our quick and easy-to-use article, you should be able to do all the basic things we have mentioned. If you have any further questions that we did not cover, leave us a comment and we try to write back as soon as possible!

Источник

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