Mac os zsh path

Использование переменных среды в Терминале на Mac

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

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

Чтобы задать значение для переменной среды, свяжите имя переменной с требуемым значением при помощи соответствующей команды shell. Например, чтобы задать для переменной PATH значение /bin:/sbin:/user/bin:/user/sbin:/system/Library/ , необходимо ввести следующую команду в окне «Терминала».

Чтобы просмотреть все переменные среды, введите:

При запуске приложения из shell приложение наследует значительную часть среды shell, в том числе экспортированные переменные среды. Эта форма наследования может быть полезна для динамической настройки приложения. Например, приложение может проверить наличие (или значение) переменной среды и изменить свою работу соответствующим образом.

Различные shell поддерживают различные семантики для экспорта переменных среды. Cм. man‑страницу предпочитаемой Вами оболочки shell.

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

После закрытия окна Терминала все переменные, которые Вы задали в этом окне, больше не доступны. Если Вы хотите, чтобы значение переменной сохранялось между различными сеансами и во всех окнах Терминала, настройте ее в загрузочном скрипте shell. Об изменении загрузочного скрипта оболочки zsh для сохранения переменных и других настроек между сеансами см. в разделе Invocation на man-странице оболочки zsh.

Источник

How to Add to the Shell Path in macOS Big Sur and Catalina using Terminal

The shell path for a user in macOS is a set of paths in the filing system whereby the user has permissions to use certain applications, commands and programs without the need to specify the full path to that command or program in the Terminal.

So instead of running something like this, with a path to the command or script:

You can just type the command, regardless of where you are in the filing system:

Your shell path is a bunch of absolute paths of the filing system separated by colons :

You can find out whats in your path by launching Terminal in Applications/Utilities and entering:

And the result should be like this..(the last one when you have Xcode)

So this is stating that you can run Unix style applications or commands located in 5 or 6 default locations of a certain path in the filing system:

  • /usr/local/bin
  • /usr/bin
  • /bin
  • /usr/sbin
  • /sbin
  • /Library/Apple/usr/bin (If you have Xcode)
Читайте также:  Как узнать скольки разрядный windows 32 или 64

These directories are not visible by default in the filing system but you can make them visible.

Adding a Temporary Location

You can add extra locations to your path, in the myscript.sh example above it’s location /Users/yourusername/bin/ which is not in the default path, you can add it in Terminal like so:

So here I have copied my existing path and added the new location on the end, colon separate the paths. Test it by running echo $PATH again in the Terminal.

One of the disadvantages of this is that the new location will only be honored for that particular Terminal session, when a new Terminal window is launched it will have the original default path again.

Adding in a Permanent Location

To make the new path stick permanently you need to add or edit a .zshrc file or a .bash_profile or .bashrc in your home directory and add to the path there.

This configuration file controls various Terminal environment preferences including the path.

In macOS Big Sur and Catalina the default shell is Zsh aka the Z Shell which has the .zshrc file to control it (previously it was the Bash Shell using .bash_profile or .bashrc ).

This command moves you into home directory, if you are already in the home directory then you are in the right spot. Check you have a .zshrc file by running the ls -la command which shows the directory files.

If you don’t have it, create it and edit it with a command line editor called nano:

If you do have it just edit it:

Add in the above line which declares the new location /Users/yourusername/bin as well as prefixing the original path declared as $PATH.

Also if you have an existing .zshrc file it may have these lines in it:

Just uncomment the second line

Add in any extra paths colon separating them with no trailing slash

Saving the Edits in Nano

Save the file in nano by clicking ‘control’ +’o’ and confirming the name of the file is .zshrc by hitting return. And the ‘control’+’x’ to exit nano.

Either refresh the .zshrc file by using source or restart the Terminal:

So now when the Terminal is relaunched or a new window made and you check the the path by

You will get the new path at the front followed by the default path locations, all the time

Rearranging the default $PATH

If you needed to rearrange the paths in the default $PATH variable, you can just do that and leave off $PATH.

So lets say you want /usr/local/bin at the beginning to take precedence you can add the default path like so inside .zshrc

And then you can slot in other paths as required.

Источник

Настройка ZSH в Mac OS

Mar 22, 2017 · 1 min read

С недавних пор начал использовать Mac OS, почти сразу подумал, что стандартный терминал не очень-то и удобен.

Читайте также:  Special pool detected memory corruption windows 10 как исправить

В качестве оболочки будем использовать ZSH, о нём, думаю, не слышал только любитель красивых UI, а вместо стандартного терминала я использую iTerm2.

В Mac OS ZSH предустановлен, поэтому сразу устанавливаем его в качестве оболочки по умолчанию с помощью команды chsh -s /bin/zsh . После перезапуска терминала оболочкой должен быть уже ZSH, если попросит начать настройку, то прервём сей процесс, нажав q.

Ручками мы писать конфиги, разумеется, не будем, пусть это сделает “Oh My Szh”. Переходим в домашний каталог и выполняем:

След у ющим шагом откроем для редактирования файл

/.zshrc и изменим значение параметра ZSH_THEME на agnoster , сохраняемся и перезапускаем терминал. В этот момент вы, скорее всего, увидите криво (никак) отображаемые символы, всё это происходит из-за некоторых отсутствующих шрифтов в системе, исправим это:

  1. Скачаем архив — вот здесь .
  2. Перейдём в “ fonts-master/UbuntuMono/” и установим все шрифты в этой директории.
  3. В настройках терминала выставляем шрифт “ Ubuntu Mono derivative Powerline”.

После перезапуска терминала вы, наконец, сможете узреть нормально работающую тему “agnoster”.

Источник

Where to place $PATH variable assertions in zsh?

I love zsh , but I am not sure where to place my $PATH and other variable assertions? I find that they are scattered between the files .zshrc .zprofile .bashrc .bash_profile , and sometimes doubled.

I realize that having anything inside the bash files doesn’t make much sense seeing as I’m using zsh , but where exactly should I be placing my rvm , python , node etc additions to my $PATH ?

Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?

3 Answers 3

tl;dr version: use

And read the man page to understand the differences between:

Regarding my comment

In my comment attached to the answer kev gave, I said:

This seems to be incorrect — /etc/profile isn’t listed in any zsh documentation I can find.

This turns out to be partially incorrect: /etc/profile may be sourced by zsh . However, this only occurs if zsh is «invoked as sh or ksh «; in these compatibility modes:

The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. [man zshall, «Compatibility»].

At login, Zsh sources the following files in this order:
/etc/profile
This file is sourced by all Bourne-compatible shells upon login

This implys that /etc/profile is always read by zsh at login — I haven’t got any experience with the Arch Linux project; the wiki may be correct for that distribution, but it is not generally correct. The information is incorrect compared to the zsh manual pages, and doesn’t seem to apply to zsh on OS X (paths in $PATH set in /etc/profile do not make it to my zsh sessions).

To address the question:

where exactly should I be placing my rvm, python, node etc additions to my $PATH?

Generally, I would export my $PATH from

Читайте также:  Microsoft ru windows 10 professional 1903 x64 x86 by ovgorskiy 2019

/.zshrc , but it’s worth having a read of the zshall man page, specifically the «STARTUP/SHUTDOWN FILES» section —

/.zshrc is read for interactive shells, which may or may not suit your needs — if you want the $PATH for every zsh shell invoked by you (both interactive and not, both login and not, etc), then

/.zshenv is a better option.

Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?

There’s a bunch of files read on startup (check the linked man pages), and there’s a reason for that — each file has it’s particular place (settings for every user, settings for user-specific, settings for login shells, settings for every shell, etc).
Don’t worry about

/.zshenv not existing — if you need it, make it, and it will be read.

.bashrc and .bash_profile are not read by zsh , unless you explicitly source them from

/.zshrc or similar; the syntax between bash and zsh is not always compatible. Both .bashrc and .bash_profile are designed for bash settings, not zsh settings.

Источник

Where is the .zshrc file on Mac?

I’m using iTerm and wanted to customize the look of my terminal window using Oh My ZSH!. And according to the documentation I need to change the

/.zshrc file and add a ZSH_THEME value:

Once you find a theme that you want to use, you will need to edit the

/.zshrc file. You’ll see an environment variable (all caps) in there that looks like:

The problem is I don’t know where to find the

) refers to your home directory where .zshrc is typically installed and checked for. That’s your per-user file that you can create and change to your liking. There’s also a global config one in /etc/zshenv, but I wouldn’t touch that one.

5 Answers 5

/.zshrc doesn’t exist by default in macOS so you need to create it. The

/ translates to your user’s home directory and the .zshrc is the ZSH configuration file itself.

So just open up a Terminal — or iTerm — window and create that file like this; I am using nano as a text editor but feel free to use whatever text editor you feel comfortable with:

And then set the ZSH_THEME value to whatever value you want to use like this:

Now to save the file in nano just hit ctrl + X . When it prompts:

Save modified buffer (ANSWERING «No» WILL DESTROY CHANGES) ?

Just type “Y” and then you will get a new prompt which looks something like this; just note the path /Users/giacomo/ will match your local user’s path:

File Name to Write: /Users/giacomo/.zshrc

Now just hit return and the file will be saved and you will now be back to the command line prompt in the Terminal. If you now exit from the Terminal and then open a new window, the

Источник

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