Bashrc для mac os

About bash_profile and bashrc on macOS

Note: bash_profile is completely different from configuration profiles. Learn more about Configuration Profiles in my book: ‘Property Lists, Preferences and Profiles for Apple Administrators’

You can learn more about using Terminal and the shell on macOS in my my book: “macOS Terminal and Shell” — Thank you!

In this spontaneous series on the macOS Terminal I have often mentioned adding something as an alias or function to your bash_profile or bashrc . Obviously, you may wonder: how do I do that? And which file should I use?

When you work with the command line and the bash shell frequently, you will want to customize the environment. This can mean changing environment variables, such as where the shell looks for commands or how the prompt looks, or adding customized commands.

For example, macOS sets the PATH environment variable to /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin by default. This is a list of directories (separated by a colon ‘ : ’) that the system searches through in order for commands. I like to add a folder in my home directory

/bin to that list, so that I can execute certain tools without needing to type out the full path. (e.g. munkipkg, quickpkg and ssh-installer).

In bash you append to existing PATH do this with:

You could type this command every time you open a new Terminal window (i.e. shell), or you can configure your shell to do this automatically.

Depending on which shell you use and how you start the shell, then certain script files will be executed which allow you to set up these customizations.

This article will talk about customizing bash on macOS. Other shells and other operating systems may have other files or rules.

So, which file?

Thanks to the rich and long history of bash the answer to which file you should put your configuration in, is surprisingly confusing.

There are (mainly) two user level files which bash may run when a bash shell starts.

Both these files are on the first level of your home directory

/ . Since the file names start with a . Finder and normal ls will not show them. You need to use ls -a to see if they are present. Read more about invisible and hidden files here.

The usual convention is that .bash_profile will be executed at login shells, i.e. interactive shells where you login with your user name and password at the beginning. When you ssh into a remote host, it will ask you for user name and password (or some other authentication) to log in, so it is a login shell.

When you open a terminal application, it does not ask for login. You will just get a command prompt. In other versions of Unix or Linux, this will not run the .bash_profile but a different file .bashrc . The underlying idea is that the .bash_profile should be run only once when you login, and the .bashrc for every new interactive shell.

However, Terminal.app on macOS, does not follow this convention. When Terminal.app opens a new window, it will run .bash_profile . Not, as users familiar with other Unix systems would expect, .bashrc .

Note: The Xterm application installed as part of Xquartz runs .bashrc when a new window opens, not .bash_profile . Other third-party terminal applications on macOS may follow the precedent set by Terminal.app or not.

This is all very confusing.

There are two main approaches:

  • When you are living mostly or exclusively on macOS and the Terminal.app, you can create a .bash_profile , ignore all the special cases and be happy.
  • If you want to have an approach that is more resilient to other terminal applications and might work (at least partly) across Unix/Linux platforms, put your configuration code in .bashrc and source .bashrc from .bash_profile with the following code in .bash_profile :
Читайте также:  Module init tools linux

The if [ -r . ] tests wether a file exists and is readable and the source command reads and evaluates a file in place. Sometimes you see

(mind the spaces) Which is a shorter way to do the same thing.

Since either file can drastically change your environment, you want to restrict access to just you:

That was confusing. Is that all?

No. There are more files which may be executed when a shell is created.

When bash cannot find .bash_profile it will look for .bash_login and if that does not exist either .profile . If .bash_profile is present the succeeding files will be ignored. (though you can source them in your .bash_profile )

There is also a file /etc/profile that is run for interactive login shells (and Terminal.app). This provides a central location to configure the shells for all users on a system. On macOS /etc/profile sets the default PATH with the path_helper tool and then source s /etc/bashrc which (you guessed) would be the central file for all users that is executed for non-login interactive shells. For macOS Terminal.app /etc/bashrc sets the default prompt and then itself sources /etc/bashrc_Apple_Terminal which sets up the session persistence across logins.

So in macOS Terminal.app, before you even see a prompt, these scripts will be run:

  • /etc/profile
    • /etc/bashrc
      • /etc/bashrc_Apple_Terminal
  • if it exists:

    /.bash_profile does not exists,

    /.bash_login
    when neither

    /bash_profile can optionally source

    There is also a file

    /.inputrc , where you can setup certain command line input options. One common example for this is to enable case-insensitive tab-completion. You can find a list of more options here.

    Finally, there is

    /.bash_logout which is run when a shell exits or closes.

    Ok, so I have the file, now what?

    Whichever file you choose, (I went with option one and have everything in .bash_profile ) now you want to put stuff in it.

    Technically this is a script, so you can do anything you can code in bash . However, usually the contents of a .bash_profile or .bashrc fall into one of three categories:

    • setting environment variables, usually ones that affect shell behavior ( PATH ) or look and feel ( PS1 ) or set configuration for other commands or programs ( CLICOLOR )
    • aliases
    • functions

    I will show some examples for each in the next post!

    8 thoughts on “About bash_profile and bashrc on macOS”

    I ran across your article when trying, vainly, to get bash to use the new paths I added to the “/etc/paths” file. I notice from your little order of execution list that /etc/path isn’t listed. Could this be why it is refusing to use the paths I added? Several previous attempts, using suggestions in other terminal threads may have monkeyed with .bash_profile, because when I open it in BBEdit, it’s empty and since there was nothing in it anyway, I deleted it.

    The basic issue is that I have confirmed with 3 different text editors and the echo $PATH terminal command that my changes are indeed in the file, but when I type “mysql” or “mongo” at the shell prompt, I always get the errors: “-bash: mysql: command not found” or “-bash: mongo: command not found”. Ten hours hours of Googling, reading dozens of supposed solutions all yield the same result “command not found”. Obviously I’m missing something important, but at this point, I really have no idea what to look for or what terms to Google.

    Does anything pop to mind? I can confirm that both mysql and mongo run fine if I type the full path ie: “/usr/local/mongo/bin/mongo”, (and these are defined exactly the same in the “etc/paths” file) but the terminal doesn’t seem to use my additions.

    Any pointers greatly appreciated.

    I explain how to change the PATH for just your user in the follow-up post. This is usually easier than manipulating /etc/paths or /etc/paths.d , unless you want or need to change the PATH for all users. You can read how to work with paths.d in this article.

    Remote diagnosis is always fraught with misunderstandings and failure, but I believe you might be adding the path to the tool rather than the path to the directory containing the tool?

    PATH is a list of directories, containing the commands. Not a list to the commands themselves. So in your case, you would add /usr/local/mongo/bin to the PATH with

    in your .bash_profile .

    Anyway you do this, any change won’t be in effect until you open a new bash/Terminal window as the PATH is only evaluated when you start a new shell.

    “I believe you might be adding the path to the tool rather than the path to the directory containing the tool?”

    Bingo! As soon as I deleted the tool name > mongo started to work.

    Thanks for this useful clarification. There’s one more fun part when using Mac OS if you use screen (I’m unsure about tmux it may well be the same). A screen session will start by running `

    For this reason I usually put all my desired shell settings and aliases etc in `

    ./bash_profile` and my `

    /.bashrc` file looks like this:

    source /etc/bashrc
    source $HOME/.bash_profile

    Thank you for that clarification.

    Users will *not* have a .bash_profile file by default. It would be far less confusing if you assume this instead of having a “Ok, so I have the file, now what?” section, because pretty much nobody will. You should proceed with people needing to create it and fill a blank slate.

    Thanks for a very useful article.

    Would you know exactly what `su` does, and more specifically, `su -l`? The `man` page says that it simulates a full login, but it doesn’t say much more than that. From experimentation, it appears that it runs `.bash_profile`. Any documentation on that?

    Here is my use case. I have different accounts on my macbook pro, with prompts (PS1) customised as in the respective `.bash_profile` files. This PS1 does not get updated if I use `su`, but it does if I use `su -l`. This must mean that `su -l` runs `.bash_profile`.

    Correct, without the `-l` su will run the command given in the _current_ shell environment, i.e. the shell environment of the user running su. With the `-l` it will create a new shell environment for the user you are switching to. That will include switch to that user’s default shell and running that user’s shell configuration scripts. (and also clearing any customization your current shell may have.)

    Leave a Reply Cancel reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Источник

    Где найти файл .bashrc на Mac OS X Snow Leopard и Lion?

    Я хочу установить rvm на мою машину Snow Leopard.

    В нем говорится, что мне нужно добавить строку в мой .bashrc файл (я использую bash), но где мой .bashrc файл?

    5 ответов

    Так получается, что в Mac OS X Snow Leopard, а также в Mac OS X Lion загруженный файл называется .profile , а не .bashrc .

    Что вы хотите сделать, это создать файл в

    /.profile и вызвать его .profile (если он еще не существует).

    Поместите любую информацию, необходимую для загрузки с каждым экземпляром bash (Спасибо, thepurplepixel).

    Несколько примечаний:

    1. Период перед файлом указывает его как невидимый для Finder и команда ls по умолчанию. Список невидимых файлов с использованием ls команды из терминала, используйте -a как параметр: ls -a
    2. Символ

    обозначает /Users/YourUserName , где YourUserName это ваше имя пользователя.

    Изменить: Chris Page отмечает (правильно), что все, что вы помещаете в файл .profile, будет применяться к любой используемой оболочке (т. е. zhs, bash и т. д.). Если вы хотите, чтобы содержимое влияло только на оболочку bash, поместите содержимое в файл .bash_profile вместо файла .profile .

    Относительно проблемы с .bashrc выше:

    В большинстве систем

    /.bashrc используется только при запуске интерактивной не-login оболочки . Однако при запуске новой оболочки она обычно представляет собой интерактивную login оболочку . Поскольку это оболочка login , .bashrc игнорируется. Чтобы поддерживать согласованность среды между недействительными и логическими оболочками, вы должны указать .bashrc из вашего .profile или вашего .bash_profile .

    См. Справочное руководство по Bash, раздел 6.2 Bash Startup Файлы

    Вызывается как интерактивная оболочка входа, или с —login

    Когда Bash вызывается как интерактивный логин, или как неинтерактивный оболочка с опцией —login, она сначала считывает и выполняет команды из файл /etc /profile, если этот файл существует. Прочитав этот файл, он ищет

    /.profile, в этом порядок, чтение и выполнение команд от первого, который существует и читаемым.

    Вызывается как интерактивная оболочка без входа

    Когда запущена интерактивная оболочка, которая не является оболочкой входа, Bash считывает и выполняет команды из

    /.bashrc, если этот файл существует.

    Итак, обычно ваш

    /.bash_profile содержит строку

    после (или до) инициализации, зависящей от имени пользователя.

    На моем Mac (Running Leopard) не было строки для источника

    /.bashrc . Я должен был добавить эту функциональность самостоятельно.

    В некоторых системах и других операционных системах .bashrc поступает из глобального /etc/profile или /etc/bash_profile , или выполняется с использованием файлов шаблонов из /etc/skel .

    Честно говоря, различие между .bashrc и .bash_profile не совсем понятно сообществу. Когда многие разработчики говорят «Добавьте это в свой .bashrc», они действительно означают «Добавить это в ваш .bash_profile». Они хотят, чтобы функциональность была добавлена ​​в оболочку login (которая является .bash_profile ), а не в оболочку non-login . В действительности это обычно не имеет значения, и размещение конфигурации в .bashrc приемлемо.

    Вы должны создать свой собственный .bashrc . Вы можете просто использовать текстовый редактор, чтобы сделать файл с именем .bashrc (без расширения) с нужным содержимым и сохранить его в своем домашнем каталоге ( /Users/YourUserName/ ).

    Я обнаружил, что в моей ОС 10.6.5 настройки bash находятся в «/etc /bashrc». Я думаю, что это спецификации toplevel для оболочки.

    Однако для его изменения требуется учетная запись root. Локальные спецификации для пользователя «

    /.bashrc» должны начинаться со следующего фрагмента, чтобы читать и загружать настройки bash на системном уровне:

    Я обычно добавляю псевдонимы на уровне bashrc на уровне системы, чтобы все пользователи могли получить к ним доступ. Если они не хотят использовать ваши ярлыки и псевдонимы.

    Используйте файл .profile, чтобы добавить все, что вы добавили бы в файл Linux .bashrc.

    Источник

    Где я могу найти файл bashrc на Mac?

    Привет, я следую за этим страница.. Я устанавливаю Python на свой mac, чтобы я мог настроить Django / Eclipse среда разработки.
    Однако я не слишком уверен, как выполнить этот шаг:

    • скрипт объяснит, какие изменения он внесет и предложит вам перед началом установки.
    • после установки Homebrew, вставьте каталог Homebrew в верхней части среды PATH переменная.

    вы можете сделать это, добавив следующую строку в нижней части

    путь экспорта= / usr / local / bin:$PATH

    где я могу найти файл bashrc на моем mac и где я могу найти каталог homebrew?

    Я macbook pro с OS 10.8.5 .

    4 ответов

    The .файл bashrc в домашнем каталоге.

    Итак, из командной строки сделайте:

    это покажет все скрытые файлы в вашем домашнем каталоге. «cd» доставит вас домой, а ls-A будет «перечислять все».

    В общем, когда вы видите

    / Тильда косая черта относится к вашему домашнему каталогу. Так./

    bashrc ваш домашний каталог с .файл bashrc.

    и стандартный путь к homebrew находится в /usr / local / so, если вы:

    вы должен увидеть каталог homebrew (/usr / local / homebrew). источник

    да иногда вам может потребоваться создать этот файл и типичный формат .файл bashrc:

    если вы создаете свой собственный .файл bashrc убедитесь, что следующие строки в ваш

    Я думаю, вы должны добавить его в

    /.bash_profile вместо .bashrc , (создание .bash_profile если он не существует.) Тогда вам не нужно добавлять дополнительный шаг проверки для

    /.bashrc в своем .bash_profile

    тебе удобно работать и редактировать в терминале? На всякий случай,

    / означает ваш домашний каталог, поэтому, если вы откроете новое окно терминала, где вы будете «расположены». И точка на передней панели делает файл невидимым для normal ls команда, если вы не ставите -a или укажите имя файла.

    /.bashrc Это уже путь к .bashrc .

    если у вас echo

    вы увидите, что это путь к вашей домашней директории.

    Homebrew каталог является /usr/local/bin . Homebrew установлен внутри него, и все, что установлено homebrew, будет установлено там.

    например, если вы делаете brew install python Homebrew поместит двоичный файл Python в /usr/local/bin .

    наконец, чтобы добавить каталог Homebrew в свой путь, вы можете запустить echo «export PATH=/usr/local/lib:$PATH» >>

    /.bashrc . Это создаст

    открыть терминал и выполните команды, приведенные ниже.

    subl обозначает редактор Sublime. Вы можете заменить subl С vi открыть файл bashrc в Редакторе по умолчанию. Это тренировки только если у вас есть файл bashrc, созданный ранее.

    Источник

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