Export path in .profile on mac
I can’t believe there isn’t any tutorials about this after googling. Can someone point me a direction or explain what these lines and variables mean in .profile on mac? How can someone configure them?
3 Answers 3
Any line starting with # is a comment. PATH= sets the value of the PATH variable, $PATH expands to the current value, and the export at the beginning makes the value available to programs that you run from the terminal.
Let’s assume that the initial value of PATH is /usr/bin:/bin .
Replace $PATH with the previous value of $PATH. So the above sets PATH to
Again, replace $PATH with the previous value:
is a special token that will be replaced with the path to your home directory, but you should get the picture.)
PATH is used to find commands that you enter on the command line. So if you type foo , the shell will look for the names below, in the order specified:
To see the current value of PATH, run
Should you add new directories to the beginning of PATH , or to the end? It doesn’t always matter, but sometimes it does. It depends on which locations you want the system to check first.
You should add to the beginning if the goal is to search other directories before looking in the default ones. For example, git is a utility used to manage source code. If I wanted to install a newer version of git in
/git and use that by default, I’d do:
/git/bin/git would override /opt/local/bin/git.
On the other hand I might prefer to have the administrator install git system-wide. If I want to use my local copy only until the administrator makes it available for everyone, then this makes more sense:
/git/bin/git would only be used if /opt/local/bin/git didn’t already exist since /opt/local/bin is earlier in the path.
A lot of commands won’t exist in more than one place. For example you might write my-backup-script and put it on an Apple Time Capsule at /Volumes/Capsule/scripts . It’s not likely that there would be a command called my-backup-script in any other location to conflict. So either of the following commands would let you type my-backup-script and run the right script:
Is one better? My advice would be to do the latter. Remember that system will need to search the directories in $PATH , in order, for every command that it needs to find. Most commands will be on the local system, so it makes the most sense to put slower network storage at the end of the path.
Bash: Как в macOS добавить новую переменную $PATH?
Сегодня рассказываем вам как добавить новую переменную $PATH в операционной системе macOS (OS X).
Если вам надоело в «Терминале» macOS каждый раз вводить определенные команды через ./команда , тогда необходимо добавить переменную окружения. То есть вам необходимо вам необходимо внести путь полный к команде утилиты в файл .bash_profile .
Как узнать полный путь к команде?
Есть два варианта узнать полный путь, где находиться утилиты с соответствующей командой.
С помощью доп.меню
Сделайте «правый клик» по папке, где находится команда и при появлении контекстного меню нажмите кнопку ALT (OPTION) и «Скопируйте путь до».
С помощью терминала
Перетяните папку с командой в «Терминал» после чего вы сможете скопировать полный путь.
Как добавить переменную окружения в macOS?
Есть также 4 варианта — первый, это открытие файла .bash_profile с помощью Finder и внесение пути, второй и третий и четвертый с помощью терминала:
Добавить переменную в файл .bash_profile
Откройте ваш домашний каталог:
Редактируем .bash_profile :
Добавьте в файл такую запись:
Закройте текстовый файл, все готово!
У вас остались еще дополнительные вопросы? Пишите их в комментариях, о том что у вас получилось или наоборот!
Вот и все! Больше полезных статей и инструкций читайте в разделе Статьи и Хаки IOS и macOS. Оставайтесь вместе с сайтом Android +1, дальше будет еще интересней!
editing PATH variable on mac [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed 7 years ago .
How to edit PATH variable on mac (Lion). I cannot find any file where I can add paths. can someone guide me about it?
Whats the file name? .profile or .bash_profile.
and where I can find it? I have tried
5 Answers 5
Edit /etc/paths . Then close the terminal and reopen it.
Note: each entry is seperated by line breaks.
Based on my own experiences and internet search, I find these places work:
Note that you should open a new terminal window to see the changes.
You may also refer to this this question
You could try this:
- Open the Terminal application. It can be found in the Utilities directory inside the Applications directory.
- Type the following: echo ‘export PATH=YOURPATHHERE:$PATH’ >>
/.profile, replacing «YOURPATHHERE» with the name of the directory you want to add. Make certain that you use «>>» instead of one «>».
Использование переменных среды в программе «Терминал» на Mac
Shell использует переменные среды для хранения информации, такой как имя текущего пользователя, имя хоста и пути по умолчанию к любым командам. Переменные среды наследуются всеми командами, которые исполняются в контексте shell, и некоторыми командами, которые зависят от переменных среды.
Вы можете создать переменные среды и использовать их для управления работой команды, не изменяя саму команду. Например, с помощью переменной среды можно сделать так, чтобы команда печатала отладочную информацию в консоль.
Чтобы задать значение для переменной среды, свяжите имя переменной с требуемым значением при помощи соответствующей команды shell. Например, чтобы задать для переменной PATH значение /bin:/sbin:/user/bin:/user/sbin:/system/Library/ , необходимо ввести следующую команду в окне «Терминала».
Чтобы просмотреть все переменные среды, введите:
При запуске программы из shell программа наследует значительную часть среды shell, включая экспортированные переменные среды. Эта форма наследования может быть полезна для динамической настройки приложения. Например, программа может проверить наличие (или значение) переменной среды и изменить свою работу соответствующим образом.
Различные shell поддерживают различные семантики для экспорта переменных среды. Информацию см. на man-странице предпочитаемой shell.
Несмотря на то что дочерние процессы shell наследуют среду этой shell, различные shell имеют раздельные контексты исполнения, которые не делятся друг с другом информацией о среде. Переменные, заданные в одном окне Терминала, не передаются в другие окна Терминала.
После закрытия окна Терминала все переменные, которые Вы задали в этом окне, больше не доступны. Если Вы хотите, чтобы значение переменной сохранялось между различными сеансами и во всех окнах Терминала, настройте ее в загрузочном скрипте shell. Об изменении загрузочного скрипта оболочки zsh для сохранения переменных и других настроек между сеансами см. в разделе Invocation на man-странице оболочки zsh.
Setting PATH environment variable in OSX permanently
I have read several answers on how to set environmental variables on OSX as permanently.
First, I tried this, How to permanently set $PATH on Linux/Unix? but I had an error message saying no such file and directory , so I thought I could try
/.bash_profile instead of
/.profile but it did not work.
Second, I found this solution How to set the $PATH as used by applications in os x , which advices to make changes in
but again I had no such file and directory error.
I need a way to set these variables such that it won’t require to set them again and again each time I open a new terminal session.
/.profile most *nix systems recognize the file and use it if it exists. you might need a reboot though – trve.fa7ad Jun 6 ’16 at 12:02
/.MacOSX/environment.plist is deprecated. – Pierre ALBARÈDE Apr 8 ’18 at 17:46
6 Answers 6
You have to add it to /etc/paths .
Reference (which works for me) : Here
I’ve found that there are some files that may affect the $PATH variable in macOS (works for me, 10.11 El Capitan), listed below:
As the top voted answer said, vi /etc/paths , which is recommended from my point of view.
Also don’t forget the /etc/paths.d directory, which contains files may affect the $PATH variable, set the git and mono-command path in my case. You can ls -l /etc/paths.d to list items and rm /etc/paths.d/path_you_dislike to remove items.
If you’re using a «bash» environment (the default Terminal.app , for example), you should check out
/.bashrc . There may be not that file yet, but these two files have effects on the $PATH .
If you’re using a «zsh» environment (Oh-My-Zsh, for example), you should check out
And don’t forget to restart all the terminal windows, then echo $PATH . The $PATH string will be PATH_SET_IN_3&4:PATH_SET_IN_1:PATH_SET_IN_2 .
Noticed that the first two ways ( /etc/paths and /etc/path.d ) is in / directory which will affect all the accounts in your computer while the last two ways (
/ directory (aka, /Users/yourusername/ ) which will only affect your account settings.
PATH (MacOS) : Best practice for PATH Environment Variables On Mac OS 🔥
As you know Mac is a wonderful OS, if you are using MacOS, you may need to know how to edit your PATH environment. The good news is that this is an easy task on Mac OS
1. What are Environment Variables?
Environment variables are global system variables accessible by all the processes/users running under the Operating System (OS), such as Windows, macOS and Linux. Environment variables are useful to store system-wide values, for examples,
- PATH : the most frequently-used environment variable, which stores a list of directories to search for executable programs.
- OS : the operating system.
- COMPUTENAME , USERNAME : stores the computer and current user name.
- SystemRoot : the system root directory.
- (Windows) HOMEDRIVE , HOMEPATH : Current user’s home directory.
2. (macOS/Linux) Environment Variables
E nvironment variables in macOS/Unixes are case-sensitive. Global environment variables (available to ALL processes) are named in uppercase, with words joined with underscore ( _ ), e.g., JAVA_HOME . Local variables (available to the current process only) are in lowercase. The recommended way is by editing your .bash_profile file. This file is read and the commands in it executed by Bash every time you log in to the system. The best part is that this file is specific to your user so you won’t affect other users on the same system by changing it.
2.1 — Using Environment Variables in Bash Shell
Most of the Unixes (Ubuntu/macOS) use the so-called Bash shell. Under bash shell:
- To list all the environment variables, use the command “ env » (or » printenv «). You could also use » set » to list all the variables, including all local variables.
- To reference a variable, use $ varname , with a prefix ‘$’ (Windows uses % varname% ).
- To print the value of a particular variable, use the command “ echo $ varname «.
- To set an environment variable, use the command “ export varname=value «, which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces.
- To set a local variable, use the command “ varname= value » (or » set varname= value «). Local variable is available within this process only.
- To unset a local variable, use command “ varname= «, i.e., set to empty string (or » unset varname «).
2.2 — How to Set an Environment Variable Permanently in Bash Shell
You can set an environment variable permanently by placing an export command in your Bash shell’s startup script «
/.profile «) of your home directory; or » /etc/profile » for system-wide operations. Take note that files beginning with dot ( . ) is hidden by default. To display hidden files, use command » ls -a » or » ls -al «.
For example, to add a directory to the PATH environment variable, add the following line at the end of «
denotes the home directory of the current user, or » /etc/profile » for ALL users.
Step 1: Open up a Terminal window
Step 2: Enter the follow commands: