- Использование переменных среды в Терминале на Mac
- MacOS: Set / Change $PATH Variable Command
- macOS (OS X): Change your PATH environment variable
- Method #1: $HOME/.bash_profile file
- Method #2: /etc/paths.d directory
- Conclusion
- Где установить переменные окружения в Mac OS X 2021
- Полный обзор Mac OS X 10.11 El Capitan
- Отображение текущей среды и переменных оболочки в Mac OS X
- Установка переменных среды в командной строке Mac OS X
- Установка Временных переменных среды в OS X
Использование переменных среды в Терминале на 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.
Источник
MacOS: Set / Change $PATH Variable Command
I need to add dev tools (such as JDK and friends) to my PATH. How do I change $PATH variable in OS X 10.8.x? Where does $PATH get set in OS X 10.8 Mountain Lion or latest version of macOS?
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Apple macOS or OS X with Bash |
Est. reading time | 3 mintues |
Here is what I see
Fig.01: Displaying the current $PATH settings using echo / printf on OS X
macOS (OS X): Change your PATH environment variable
You can add path to any one of the following method:
- $HOME/.bash_profile file using export syntax.
- /etc/paths.d directory.
Method #1: $HOME/.bash_profile file
The syntax is as follows:
In this example, add /usr/local/sbin/modemZapp/ directory to $PATH variable. Edit the file $HOME/.bash_profile , enter:
vi $HOME/.bash_profile
OR
vi
/.bash_profile
Append the following export command:
Save and close the file. To apply changes immedialty enter:
source $HOME/.bash_profile
OR
. $HOME/.bash_profile
Finally, verify your new path settings, enter:
echo $PATH
Sample outputs:
Method #2: /etc/paths.d directory
Apple recommends the path_helper tool to generate the PATH variable i.e. helper for constructing PATH environment variable. From the man page:
The path_helper utility reads the contents of the files in the directories /etc/paths.d and /etc/manpaths.d and appends their contents to the PATH and MANPATH environment variables respectively.
(The MANPATH environment variable will not be modified unless it is already set in the environment.)
Files in these directories should contain one path element per line.
Prior to reading these directories, default PATH and MANPATH values are obtained from the files /etc/paths and /etc/manpaths respectively.
To list existing path, enter:
ls -l /etc/paths.d/
Sample outputs:
You can use the cat command to see path settings in 40-XQuartz:
cat /etc/paths.d/40-XQuartz
Sample outputs:
To set /usr/local/sbin/modemZapp to $PATH, enter:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
OR use vi text editor as follows to create /etc/paths.d/zmodemapp file:
sudo vi /etc/paths.d/zmodemapp
and append the following text:
Save and close the file. You need to reboot the system. Alternatively, you can close and reopen the Terminal app to see new $PATH changes.
Conclusion
- Use $HOME/.bash_profile file when you need to generate the PATH variable for a single user account.
- Use /etc/paths.d/ directory via the path_helper tool to generate the PATH variable for all user accounts on the system. This method only works on OS X Leopard and higher.
See also:
- Customize the bash shell environments from the Linux shell scripting wiki.
- UNIX: Set Environment Variable
- Man pages – bash(1), path_helper(8)
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
thank you for this.
to append multiple executables in one group, e.g ‘modemZapp2’:
sudo -s ‘echo “/usr/local/sbin/modemZapp2” >> /etc/paths.d/zmodemapp’
Thank you for your useful article! It helped me a lot!
I cannot get this to work. You write “Save and close the file”. How do I do this please?
The author does not explain this but the commands ‘vi’ in the terminal starts an editor called vim. According to the link below you can just type ‘:x’ (without the ‘) and then enter to save and close at the same time
I would like to be able to use gcc to compile a file.
I see gcc-4.0 and gcc-4.2 in /Developer/usr/bin/
echo “$PATH” gives me this:
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/MacGPG2/bin:/usr/X11/bin
If I need to set the path also to /Developer/usr/bin/ where my gcc is (I mean I guess I have to do that, not even sure) I am kind of lost. I append this:
vi $HOME/.bash_profile
Then I see in he Terminal many line breaks with
in front, the cursor is before all these breaks and at the bottom I read “”
/.bash_profile” [New File]” (in my firs attempts it was written “INSERT”).
If I paste “export PATH=$PATH:/Developer/usr/bin” there, I don’t know how to go further. If I then paste “source $HOME/.bash_profile” after, I get a mess: I had to re-install xcode everytime I messed up with the Terminal which kept on scrolling and scrolling with error messages.
Actually as soon as I paste “export PATH=$PATH:/Developer/usr/bin”, he word “INSERT” comes up at the bottom replacing ”
/.bash_profile” [New File]”
So I guess from now on I should save my new bash_profile, bu I do not know how.
I got it to work. gcc never worked, but g++ did.
Now the ./a.out command form the script I want to create is not working. Nerverending story. FIle not found no matter where my source file is.
When I did echo “$PATH”, I got
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
In my .bash_profile file, I have put
PATH=”/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:$PATH”
export PATH
But, when ever I execute a command, I need to give the full path in the command. For example,
when I take update in SVN. The command should be “svn update” but in my case i need to give “/usr/local/bin/svn update”. It happens for me in every command.
FYI: I am using OS X Yosemite, 10.10.3
Is there anything I need to change in resolving this issue ? Thanks in advance.
The reason why this is happening is because you are not pointing your “$PATH” to a folder with ONLY Mach-O 64-bit executable x86_64. In order to do this, please follow this tutorial: https://www.objc.io/issues/6-build-tools/mach-o-executables/. Long story short, to make for example an executable file from a C file “.c”, use the terminal tool xcrun with clang as an argument followed by the name of your “.c” file…This will look something like xcrun clang helloworld.c. This in turn will generate the desired “Mach-O 64-bit executable x86_64”. The file will look something like: a.out (“The file is called ‘a’ because it is the default name if given no parameters for such”). Now you can take this “a.out” file and rename it to whatever you want your command to be when you are calling it from terminal. Now after renaming your file, put it in a folder where ONLY Mach-O 64-bit executable x86_64 will be located and put this folder in your “$PATH” using any of the options listed in this article and finito!. Now you can call your file with the desired named from the terminal.
Conclusion : If you want additional values to your path for all users, you just have to create a new file in /etc/paths.d and put, on per line, additional paths that are required.
Conclusion : Specific roles taken up from time to time by users could need different environment settings. Ex – Dev role by the administrator could need the XAMP stack, and access to executing Apache, MySQL and PHP. Though Apache and PHP come built-in along with Yosemite, their bin directories are not set in the PATH variable.
Hence, we can have .bash_profile_dev in the HOME of the administrator, with all the PATH settings and command line conveniences for starting / stopping servers, etc as the need arises. This can be executed whenever the user needs to change their role, by running
Worked on my M1 MacBook Air too. Cheers mate.
Источник
Где установить переменные окружения в Mac OS X 2021
Полный обзор Mac OS X 10.11 El Capitan
В командной строке переменные среды определяются для текущей оболочки и становятся наследуемыми любой запущенной командой или процессом. Они могут определять что угодно, от оболочки по умолчанию, PATH, домашнего каталога пользователей, до типа эмуляции терминала, текущего рабочего каталога, в котором находится файл истории, настройки языка и локализации, и далее включать переменные оболочки, которые включают все от настроек до приглашения bash, цветного вывода ls, изменений внешнего вида терминала, псевдонимов и многого другого.
Давайте рассмотрим, как перечислять переменные среды и оболочки, а затем как устанавливать и добавлять новые переменные среды в командной строке Mac OS X.
Отображение текущей среды и переменных оболочки в Mac OS X
Чтобы быстро получить список переменных среды, вы можете использовать следующую команду:
Если вы хотите увидеть полный список переменных оболочки, можно также выполнить команду ‘set’:
Вывод этих команд может быть длинным, поэтому вы можете захотеть передать вывод через команды less или more.
Установка переменных среды в командной строке Mac OS X
Поскольку по умолчанию Mac использует оболочку bash, вы можете установить переменные окружения в пользовательских каталогах .bash_profile, для активной учетной записи пользователя путь к этому файлу находится по адресу:
Если вы изменили свою оболочку или не уверены, какую оболочку вы используете, вы всегда можете проверить, введя команду echo $ SHELL, которая покажет, какая оболочка используется. Мы предполагаем, что вы все еще используете оболочку bash по умолчанию для OS X, поэтому мы добавим новые переменные окружения, изменив .bash_profile с помощью nano — вы можете использовать vi, emacs или другой текстовый редактор, если хотите, но мы рассмотрим нано для простоты.
Начните с открытия .bash_profile в текстовом редакторе nano:
Вы можете добавить переменные окружения и переменные оболочки в новые строки, если в файле .bash_profile уже есть данные, просто обязательно добавьте новые переменные в новую пустую строку, используя при необходимости клавиши со стрелками и клавишу возврата.
Давайте возьмем пример и скажем, что мы собираемся установить переменные окружения JAVA_HOME и JRE_HOME в .bash_profile, добавив следующее в новые строки файла:
export JAVA_HOME=$(/usr/libexec/java_home)
export JRE_HOME=$(/usr/libexec/java_home)
Предполагая, что мы закончили, сохраните изменения, внесенные в .bash_profile, нажав Control + o (это o, как в выдре), затем выйдите из nano, нажав Control + X
Изменения и дополнения, внесенные в переменные среды, потребуют перезапуска оболочки или появления новой оболочки.
Установка Временных переменных среды в OS X
Стоит отметить, что вы также можете установить временные переменные среды в bash, используя саму команду «export», хотя они будут сохраняться только до тех пор, пока текущая оболочка bash остается активной. Например, если вы хотите добавить временный путь к
/ bin /, вы можете использовать следующую команду:
Опять же, команда «export», запускаемая сама по себе и не содержащаяся в .bash_profile, будет только временной настройкой, и переменная среды не будет сохраняться, пока вы не добавите ее в .bash_profile.
Если вы действительно хотите добавить новый PATH для использования, вы почти наверняка должны добавить его в .bash_profile, поместив соответствующую команду экспорта в файл.
Выходя за пределы оболочки bash, если вы изменили стандартную оболочку приложения терминала с bash на tcsh, zsh, sh, ksh, fish или любую другую альтернативную оболочку, вам просто нужно изменить соответствующий профиль или файл rc. для этой конкретной оболочки (.tschrc, .cshrc, .profile и т. д.).
Источник