Как изменить path mac

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 ...

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

echo 'export PATH=/android-sdk/tools:$PATH' >> ~/.profile

asked Oct 9, 2011 at 11:00

coure2011's user avatar

coure2011coure2011

39k79 gold badges213 silver badges337 bronze badges

3

Open and edit /etc/paths using any text editor.

$ sudo vi /etc/paths

(editing text files with vi)

Note: each entry is separated by a new line

/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin

Save and close the file. Then restart your terminal.

answered Apr 29, 2013 at 21:42

Ryan Allen's user avatar

Ryan AllenRyan Allen

5,1254 gold badges25 silver badges33 bronze badges

3

Based on my own experiences and internet search, I find these places work:

/etc/paths.d

~/.bash_profile

Note that you should open a new terminal window to see the changes.

You may also refer to this this question

Community's user avatar

answered Oct 31, 2012 at 1:58

can.'s user avatar

can.can.

2,0268 gold badges29 silver badges41 bronze badges

environment.plst file loads first on MAC so put the path on it.

For 1st time use, use the following command

export PATH=$PATH: /path/to/set

Peyman Mohamadpour's user avatar

answered Dec 28, 2012 at 6:47

Jay Sampat's user avatar

Jay SampatJay Sampat

1951 silver badge8 bronze badges

2

You could try this:

  1. Open the Terminal application. It can be found in the Utilities directory inside the Applications directory.
  2. 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 «>».
  3. Hit Enter.
  4. Close the Terminal and reopen. Your new Terminal session should now use the new PATH.

Quoted from ketio.me tutorial (archived copy).

zcoop98's user avatar

zcoop98

2,4651 gold badge18 silver badges31 bronze badges

answered Oct 9, 2011 at 11:03

Tobias's user avatar

TobiasTobias

9,0943 gold badges24 silver badges30 bronze badges

1

use

~/.bash_profile

or

~/.MacOSX/environment.plist

(see Runtime Configuration Guidelines)

Peyman Mohamadpour's user avatar

answered Oct 11, 2011 at 7:13

cody's user avatar

codycody

3,2131 gold badge21 silver badges24 bronze badges

I have read several answers on how to set environment variables on OSX 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 advises to make changes in

~/.MacOSX/environment.plist

but again I had no such file and directory error.

I need a way to set these variables such that it won’t require setting them again and again each time I open a new terminal session.

hippietrail's user avatar

hippietrail

15.5k18 gold badges97 silver badges153 bronze badges

asked Mar 17, 2014 at 21:02

patti_jane's user avatar

2

You have to add it to /etc/paths.

Reference (which works for me) : Here

answered Mar 17, 2014 at 21:06

Nitish's user avatar

NitishNitish

5,9981 gold badge15 silver badges15 bronze badges

7

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:

  1. As the top voted answer said, vi /etc/paths, which is recommended from my point of view.

  2. 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.

  3. If you’re using a «bash» environment (the default Terminal.app, for example), you should check out ~/.bash_profile or ~/.bashrc. There may be not that file yet, but these two files have effects on the $PATH.

  4. If you’re using a «zsh» environment (Oh-My-Zsh, for example), you should check out ~./zshrc instead of ~/.bash* thing.

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 (~/.bash* or ~/.zsh*) is in ~/ directory (aka, /Users/yourusername/) which will only affect your account settings.

Read more: Mac OS X: Set / Change $PATH Variable — nixCraft

Matthew Hinea's user avatar

answered Jul 30, 2016 at 5:57

iplus26's user avatar

iplus26iplus26

2,44715 silver badges25 bronze badges

5

For a new path to be added to PATH environment variable in MacOS just create a new file under /etc/paths.d directory and add write path to be set in the file. Restart the terminal. You can check with echo $PATH at the prompt to confirm if the path was added to the environment variable.

For example: to add a new path /usr/local/sbin to the PATH variable:

cd /etc/paths.d
sudo vi newfile

Add the path to the newfile and save it.

Restart the terminal and type echo $PATH to confirm

Patrick Mevzek's user avatar

answered Jul 6, 2018 at 22:19

XXX's user avatar

XXXXXX

8007 silver badges15 bronze badges

4

You can open any of the following files:

  • /etc/profile
  • ~/.bash_profile
  • ~/.bash_login (if .bash_profile does not exist)
  • ~/.profile (if .bash_login does not exist)

And add:

export PATH="$PATH:your/new/path/here"

wjandrea's user avatar

wjandrea

26.2k8 gold badges57 silver badges78 bronze badges

answered Jul 11, 2017 at 5:06

Bitcoin Cash - ADA enthusiast's user avatar

You could also add this

if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

to ~/.bash_profile, then create ~/.bashrc where you can just add more paths to PATH. An example with .

export PATH=$PATH:.

answered Mar 17, 2014 at 21:18

omoman's user avatar

omomanomoman

8496 silver badges10 bronze badges

7

If you are using zsh do the following.

  1. Open .zshrc file nano $HOME/.zshrc

  2. You will see the commented $PATH variable here

    # If you come from bash you might have to change your $PATH.

    # export PATH=$HOME/bin:/usr/local/...

  3. Remove the comment symbol(#) and append your new path using a separator(:) like this.

export
PATH=$HOME/bin:/usr/local/bin:/Users/ebin/Documents/Softwares/mongoDB/bin:$PATH

  1. Activate the change source $HOME/.zshrc

You’re done !!!

answered Feb 8, 2021 at 11:53

Ebin Xavier's user avatar

Ebin XavierEbin Xavier

3195 silver badges8 bronze badges

1

sudo nano /etc/paths

now find the path of command i am giving an example of setting path for flutter.

/Users/username/development/flutter/bin

now cntrol+x and then y . reopen the terminal and check.

answered Nov 30, 2021 at 16:26

Amit Kumar's user avatar

Amit KumarAmit Kumar

1,32913 silver badges8 bronze badges

launchctl setenv environmentvariablename environmentvariablevalue

or

launchctl setenv environmentvariablename `command that will generate value`

use proper ` and remember to restart application or terminal for the environment variable to take effect.

you can check environment variable by printenv command.

note : environment variable named path is already set by someone else so we are not appending anything to that path at all here.

answered Aug 1, 2021 at 20:21

Jainil Patel's user avatar

Jainil PatelJainil Patel

1,2266 silver badges16 bronze badges

shows all hidden files like .bash_profile and .zshrc
$ ls -a

Starting with macOS Catalina, mac uses zsh instead of bash. so by default mac uses zsh.
Check which shell running:

$ echo $SHELL
/usr/zsh
$ cd $HOME
$ open -e .zshrc

or if using vim

$ vi .zshrc

Then add it like this

$ export my_var="/path/where/it/exists"
$ export PATH=$PATH:/$my_var/bin

For example: if installed app named: myapp in /Applications
Then

export MYAPP_HOME=/Applications/myapp
export PATH=$PATH:$MYAPP_HOME/bin

or shortcut

export PATH=${PATH}:/Applications/myapp/bin

TADA you set for life !!! Thank me later

answered Oct 14, 2021 at 4:30

Topgyal Gurung's user avatar

19 October 2021.

Confirming iplus26‘s answer with one correction.

Test environment

OS: macOS 11.6 (Big Sur) x86_64

Shell: zsh 5.8


Below is the order in which the $PATH environment variable is modified:

  1. each line in etc/paths text file gets appended
  2. each line in each text file inside etc/paths.d directory gets appended
  3. finally, the $PATH is further modified in ~/.zshrc

iplus26‘s answer stated «when (you run) echo $PATH, The $PATH string will be PATH_SET_IN_3&4:PATH_SET_IN_1:PATH_SET_IN_2″ but this isn’t always the case. It will have to depend on what the script is doing inside .zshrc. E.g. If we do something like

PATH="/new/path:${PATH}"

then, the new path will be in the beginning of the path list. However, if we do something like

PATH="${PATH}:/new/path"

then, the new path will be appended at the end of the path list.

Of course, you’ll have to make sure you export the modified path in the ~/.zshrc file.

export PATH=$PATH

One handy command you could use to «pretty print» your path list is

print -l $path

This will print each path on a new line for better readability. Note $path is like $PATH except it’s delimited by a single space, instead of a colon, :.

Hopefully this can further clarify for newcomers to this thread.

answered Oct 19, 2021 at 11:32

Jin 허's user avatar

Jin 허Jin 허

111 bronze badge

For setting up path in Mac two methods can be followed.

  1. Creating a file for variable name and paste the path there under
    /etc/paths.d and source the file to profile_bashrc.
  2. Export path variable in ~/.profile_bashrc as

    export VARIABLE_NAME = $(PATH_VALUE)

AND source the the path. Its simple and stable.

You can set any path variable by Mac terminal or in linux also.

Marian Nasry's user avatar

answered Nov 2, 2017 at 7:37

Ram Krishna's user avatar

I have read several answers on how to set environment variables on OSX 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 advises to make changes in

~/.MacOSX/environment.plist

but again I had no such file and directory error.

I need a way to set these variables such that it won’t require setting them again and again each time I open a new terminal session.

hippietrail's user avatar

hippietrail

15.5k18 gold badges97 silver badges153 bronze badges

asked Mar 17, 2014 at 21:02

patti_jane's user avatar

2

You have to add it to /etc/paths.

Reference (which works for me) : Here

answered Mar 17, 2014 at 21:06

Nitish's user avatar

NitishNitish

5,9981 gold badge15 silver badges15 bronze badges

7

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:

  1. As the top voted answer said, vi /etc/paths, which is recommended from my point of view.

  2. 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.

  3. If you’re using a «bash» environment (the default Terminal.app, for example), you should check out ~/.bash_profile or ~/.bashrc. There may be not that file yet, but these two files have effects on the $PATH.

  4. If you’re using a «zsh» environment (Oh-My-Zsh, for example), you should check out ~./zshrc instead of ~/.bash* thing.

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 (~/.bash* or ~/.zsh*) is in ~/ directory (aka, /Users/yourusername/) which will only affect your account settings.

Read more: Mac OS X: Set / Change $PATH Variable — nixCraft

Matthew Hinea's user avatar

answered Jul 30, 2016 at 5:57

iplus26's user avatar

iplus26iplus26

2,44715 silver badges25 bronze badges

5

For a new path to be added to PATH environment variable in MacOS just create a new file under /etc/paths.d directory and add write path to be set in the file. Restart the terminal. You can check with echo $PATH at the prompt to confirm if the path was added to the environment variable.

For example: to add a new path /usr/local/sbin to the PATH variable:

cd /etc/paths.d
sudo vi newfile

Add the path to the newfile and save it.

Restart the terminal and type echo $PATH to confirm

Patrick Mevzek's user avatar

answered Jul 6, 2018 at 22:19

XXX's user avatar

XXXXXX

8007 silver badges15 bronze badges

4

You can open any of the following files:

  • /etc/profile
  • ~/.bash_profile
  • ~/.bash_login (if .bash_profile does not exist)
  • ~/.profile (if .bash_login does not exist)

And add:

export PATH="$PATH:your/new/path/here"

wjandrea's user avatar

wjandrea

26.2k8 gold badges57 silver badges78 bronze badges

answered Jul 11, 2017 at 5:06

Bitcoin Cash - ADA enthusiast's user avatar

You could also add this

if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

to ~/.bash_profile, then create ~/.bashrc where you can just add more paths to PATH. An example with .

export PATH=$PATH:.

answered Mar 17, 2014 at 21:18

omoman's user avatar

omomanomoman

8496 silver badges10 bronze badges

7

If you are using zsh do the following.

  1. Open .zshrc file nano $HOME/.zshrc

  2. You will see the commented $PATH variable here

    # If you come from bash you might have to change your $PATH.

    # export PATH=$HOME/bin:/usr/local/...

  3. Remove the comment symbol(#) and append your new path using a separator(:) like this.

export
PATH=$HOME/bin:/usr/local/bin:/Users/ebin/Documents/Softwares/mongoDB/bin:$PATH

  1. Activate the change source $HOME/.zshrc

You’re done !!!

answered Feb 8, 2021 at 11:53

Ebin Xavier's user avatar

Ebin XavierEbin Xavier

3195 silver badges8 bronze badges

1

sudo nano /etc/paths

now find the path of command i am giving an example of setting path for flutter.

/Users/username/development/flutter/bin

now cntrol+x and then y . reopen the terminal and check.

answered Nov 30, 2021 at 16:26

Amit Kumar's user avatar

Amit KumarAmit Kumar

1,32913 silver badges8 bronze badges

launchctl setenv environmentvariablename environmentvariablevalue

or

launchctl setenv environmentvariablename `command that will generate value`

use proper ` and remember to restart application or terminal for the environment variable to take effect.

you can check environment variable by printenv command.

note : environment variable named path is already set by someone else so we are not appending anything to that path at all here.

answered Aug 1, 2021 at 20:21

Jainil Patel's user avatar

Jainil PatelJainil Patel

1,2266 silver badges16 bronze badges

shows all hidden files like .bash_profile and .zshrc
$ ls -a

Starting with macOS Catalina, mac uses zsh instead of bash. so by default mac uses zsh.
Check which shell running:

$ echo $SHELL
/usr/zsh
$ cd $HOME
$ open -e .zshrc

or if using vim

$ vi .zshrc

Then add it like this

$ export my_var="/path/where/it/exists"
$ export PATH=$PATH:/$my_var/bin

For example: if installed app named: myapp in /Applications
Then

export MYAPP_HOME=/Applications/myapp
export PATH=$PATH:$MYAPP_HOME/bin

or shortcut

export PATH=${PATH}:/Applications/myapp/bin

TADA you set for life !!! Thank me later

answered Oct 14, 2021 at 4:30

Topgyal Gurung's user avatar

19 October 2021.

Confirming iplus26‘s answer with one correction.

Test environment

OS: macOS 11.6 (Big Sur) x86_64

Shell: zsh 5.8


Below is the order in which the $PATH environment variable is modified:

  1. each line in etc/paths text file gets appended
  2. each line in each text file inside etc/paths.d directory gets appended
  3. finally, the $PATH is further modified in ~/.zshrc

iplus26‘s answer stated «when (you run) echo $PATH, The $PATH string will be PATH_SET_IN_3&4:PATH_SET_IN_1:PATH_SET_IN_2″ but this isn’t always the case. It will have to depend on what the script is doing inside .zshrc. E.g. If we do something like

PATH="/new/path:${PATH}"

then, the new path will be in the beginning of the path list. However, if we do something like

PATH="${PATH}:/new/path"

then, the new path will be appended at the end of the path list.

Of course, you’ll have to make sure you export the modified path in the ~/.zshrc file.

export PATH=$PATH

One handy command you could use to «pretty print» your path list is

print -l $path

This will print each path on a new line for better readability. Note $path is like $PATH except it’s delimited by a single space, instead of a colon, :.

Hopefully this can further clarify for newcomers to this thread.

answered Oct 19, 2021 at 11:32

Jin 허's user avatar

Jin 허Jin 허

111 bronze badge

For setting up path in Mac two methods can be followed.

  1. Creating a file for variable name and paste the path there under
    /etc/paths.d and source the file to profile_bashrc.
  2. Export path variable in ~/.profile_bashrc as

    export VARIABLE_NAME = $(PATH_VALUE)

AND source the the path. Its simple and stable.

You can set any path variable by Mac terminal or in linux also.

Marian Nasry's user avatar

answered Nov 2, 2017 at 7:37

Ram Krishna's user avatar

Executing programs via the terminal is a quick and efficient way of carrying out operations on your Mac. It offers extended functionality and granular control over the program’s functionality and output, which would otherwise be lacking in its GUI equivalent.

set path environment variable on macos

However, launching programs via CLI sometimes also brings forth some problems. One such is the command not found error that the shell throws at you when you try to execute certain programs/commands.

Although you can temporarily overcome this by prepending your command with the program’s absolute path, this isn’t a very practical approach if you want to use that program several times.

An alternative (read efficient) solution around the problem is to set the PATH variable for this program. Follow along as we describe the PATH variable and list down the steps on how to set the PATH variable in macOS.

What is the PATH Environment Variable?

PATH or PATH variable is a type of environment variable on all Unix- and- Unix-like operating systems. Environment variables constitute name-value pairs for various programs or processes on an operating system, such as the path, locations of system programs or processes, and other essential information required by other system programs.

Talking about PATH, the variable contains a list of all the directories (for various programs added to the PATH) that the shell needs to search for to execute your requested programs through a terminal command.

Why Do You Need to Set the PATH Environment Variable?

On macOS, when you run a command in the terminal, it searches for the path of the requested program in that command inside the PATH environment variable. If a path address is found, it executes the command successfully and returns the output. If not, you get the command not found error.

Like we mentioned initially, specifying the absolute or full path of the directory where the program is installed/stored in your command is one way to overcome this error. But unfortunately, since doing so over and over would take up a lot of your time and effort, this isn’t a very efficient approach and can’t be used when you want to run commands repeatedly.

On the other hand, if you set the path for that program in the PATH variable, you can easily use it in any directory on your system without specifying its absolute path.

Basically, what this means is that instead of running your command like this:

/path/to/program/script.sh

you can simply use:

script.sh

inside any directory on the file system.

Setting the PATH variable in macOS requires using the CLI—unlike Windows, which lets you do so using both GUI and CLI. Plus, depending on your requirements, there are two ways to set the PATH on your Mac: temporary and permanent.

When you set PATH temporarily, your path changes apply only to the current session—logging out of the session reverts back the PATH to its previous state. In contrast, setting the PATH permanently will preserve your changes permanently and apply them to all your sessions—even after you start a new terminal session or restart your Mac.

With that out of the way, follow the steps in the sections below to set PATH on your Mac.

Identifying the Current PATH Entries

Before you add a program’s path to the PATH variable on your Mac, you should first identify the current entries in your system’s PATH to verify that there isn’t already an entry for the same.

To view the current PATH settings, open the Terminal app and run:

echo $PATH

path environment variable output

If you’re setting PATH for a new program/script, you can skip this step.

Setting the PATH Variable Temporarily

Once you’ve identified the current PATH entries, you can now set the PATH for any program. If you want to use/execute a program via terminal only in your current session, you can set its path temporarily using the following command:

export PATH=$PATH:absolute/path/to/program/

For example, if you want to set PATH for Python 3.6, you’d run:

export PATH=$PATH:/Library/Frameworks/Python.framework/Versions/3.6/bin

Doing so will set a temporary variable for the program, which you can use in your commands in the current terminal session or the active terminal window.

Setting the PATH Variable Permanently

In case you want to use a program regularly, you must set its path permanently. To do this, you need to access the shell’s configuration or profile file and add the program’s path to it.

Depending on the macOS version you’re running on your Mac, this can be done via either the bash shell or zsh (z shell).

  • For older macOS versions (before Catalina): bash (.bashrc or .bash_profile)
  • For macOS Catalina and later: zsh (.zshrc or .zsh_profile)

Now that you know the file where you need to add the path for your program/script, open the terminal and enter a command based on your shell:

For bash

nano ~/.bash_profile

or

nano ~/.bashrc

For zsh:

nano ~/.zsh_profile

or

nano ~/.zshrc

If the config file or profile file is missing from your system, this command will create a new one; in case it exists, it’ll open the same, and you can then edit it.

Now, all you have to do is find the full path for the program or script on the file system. For this, open the Finder and navigate to the directory where the program or script is stored or installed. Here, right-click on the program/script, press the Option key, and select Copy xyz as Pathname, where xyz is a program name.

Go back to the terminal and open the appropriate config file or profile for your shell in nano or any other text editor. Inside the file, enter the following line:

export PATH=$PATH:/path/to/directory

…where you need to replace path/to/directory with the exact path you copied in the previous step.

Or, if the file already contains path entries, append the line with a colon (:) followed by:

/path/to/directory

Hit Control + O to write your changes to the file. When prompted to confirm the file name, hit Return to proceed with the default. Press Control + X to exit the editor.

Now, verify if the path has been added by opening a terminal window and running:

echo $PATH

Finally, close the terminal window and reopen it to start a new session. Alternatively, you can run the following command to apply the changes immediately:

source ~/.bashrc

or

source ~/.bash_profile

or

source ~/.zshrc

or

source ~/.zsh_profile

Once that’s done, you should be able to run your program or script from any directory in the file system.

Add to PATH Mac: Accessing Programs From Anywhere via Terminal

With the PATH environment variable set to use the path of the program you want to use, you can now execute/access it from anywhere in the file system via the terminal. If you use Python or shell scripts to automate your workflow, setting the PATH for these scripts can simplify your life as you can now access them inside any directory without needing to specify their absolute paths.

FAQs About Setting PATH on macOS

1. How do I set an environment variable in Catalina Mac?

If you’re running macOS Catalina (or above), setting the environment variable is as simple as modifying the shell config or profile file to incorporate the path of the program/script you want to access anywhere. Since macOS uses zsh as the default shell on Catalina (and above) versions, you just need to edit either the .zshrc or .zsh_profile file and add the path of your program or script. Follow the steps earlier in the post to know the steps and the different ways to do this.

2. How do I permanently set PATH on Mac?

Setting the PATH on Mac permanently means your PATH environment variable changes aren’t limited to your current shell session, unlike the temporary variable settings. So your system’s shell can continue to access it even when you start a new session or restart your Mac. To permanently set PATH on Mac, all you have to do is open either bash files (.zshrc or .zsh_profile) or zsh files (.zshrc or .zsh_profile) and add your program or script’s PATH to it. Steps for doing which are listed in the guide above.

3. How do I find the PATH variable on a Mac?

To find the PATH variable on Mac, open a terminal window and run echo $PATH. After which, the shell will return a list of all the directories currently listed under the PATH environment variable on your Mac.

Was this article helpful?

YesNo

TechPP is supported by our audience. We may earn affiliate commissions from buying links on this site.

сбросить PATH на Mac

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

сбросить PATH на Mac

Однако, пока вы это делаете, бывают случаи, когда вы случайно испортили существующую (прочитанную по умолчанию) конфигурацию среды PATH в вашей системе. В Windows это не проблема, поскольку для восстановления состояния по умолчанию переменной PATH требуется всего один шаг.

Но если вы используете Mac, это не так просто. Итак, чтобы упростить это уравнение, вот руководство с подробным описанием шагов, необходимых для сброса переменной PATH в состояние по умолчанию.

Чтобы дать вам краткое представление о необходимости сбросить переменную PATH, рассмотрим сценарий, в котором вы случайно испортили — удалили или обновили — существующий PATH. переменная окружения на вашем Mac с неверными путями к программам.

Когда это происходит, все ваши существующие команды терминала, включая основные команды, такие как ls, cd, where, mkdir, rmdir и т. Д., Перестают работать и бросают команда не найдена ошибка. В результате терминал становится практически бесполезным, не позволяя выполнять различные системные операции.

Как сбросить переменную PATH в macOS

Сброс переменной PATH в macOS включает редактирование либо оболочка config или файл профиля оболочки и добавив к нему пути по умолчанию. Как и большинство операций в macOS, это можно сделать двумя способами: через графический интерфейс и через интерфейс командной строки.

Сброс переменной PATH в macOS через интерфейс командной строки

Поскольку установка PATH для программы или сценарий оболочки в macOS требуется взаимодействие с терминалом; вы, вероятно, испортили свой PATH где-то по пути. И, следовательно, очевидный способ сбросить его — через сам терминал.

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

Введите следующую команду в терминал и нажмите Возвращение чтобы временно установить ПУТЬ:

export PATH=$PATH:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

Затем откройте файл конфигурации или файл профиля для вашей оболочки. Если вы используете более старые версии macOS (до Catalina), оболочка по умолчанию в вашей системе трепать, в этом случае вы можете открыть .bashrc или .bash_profile файл. В более новых версиях macOS (Catalina или выше) у вас будет zsh (или z оболочка) в качестве оболочки по умолчанию — если вы не изменили ее на bash. Итак, вы должны отредактировать либо .zhrc или .zsh_profile файл.

Теперь, в зависимости от используемой оболочки, выполните любую из следующих команд:

Для bash

nano ~/.bash_profile

или
nano ~/.bashrc

Для zsh

nano ~/.zsh_profile

или
nano ~/.zshrc

Оказавшись внутри любого из этих файлов, вам нужно добавить все пути по умолчанию в переменную среды PATH, используя следующую команду:
export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

сбросить Mac PATH через CLI

Ударять Ctrl + O написать свои изменения. Когда будет предложено подтвердить имя файла, нажмите Return. Нажмите Ctrl + X для выхода из редактора.

Закройте активное окно терминала и снова откройте его, чтобы начать новый сеанс. В качестве альтернативы вы можете запустить команду ниже, чтобы немедленно применить изменения:

source ~/.bashrc

или
source ~/.bash_profile

Заменять .bashrc или .bash_profile с участием .zshrc или .zsh_profile если оболочка вашей системы по умолчанию — zsh.

Наконец, проверьте, правильно ли установлен PATH и сбросьте настройки PATH до значений по умолчанию, выполнив:
echo $PATH

просмотр записей PATH в macOS по умолчанию

Если оболочка возвращает список всех различных путей, это означает, что ваша переменная среды PATH была сброшена, и поэтому вы можете возобновить использование на ней различных команд терминала macOS, как и раньше.

Сброс переменной PATH в macOS через графический интерфейс

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

Для этого откройте Finder и перейти к корневой каталог> Пользователи> каталог your_user_account и ударил Command + Shift +. ярлык для просмотра всех скрытых в нем файлов.

сбросить Mac PATH через графический интерфейс

Затем, в зависимости от активной оболочки в вашей системе, найдите любой из следующих файлов: .bashrc, .bash_profile, .zshrc, или .zsh_profile. Щелкните файл правой кнопкой мыши и выберите Открыть с помощью> TextEdit.

сбросить Mac PATH через графический интерфейс

Когда файл откроется в TextEdit, скопируйте следующую строку и вставьте ее в файл:
export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

сбросить Mac PATH через графический интерфейс

Ударять Command + S сохранить изменения в файле и Command + W чтобы закрыть файл.

Успешный сброс переменной PATH на Mac

Изменить или установить переменную среды PATH на Mac непросто, если у вас нет предыдущего опыта, и вы рискуете нарушить функциональность терминала из-за неправильного изменения (удаления / добавления / редактирования) записей в файлах конфигурации PATH.

Поэтому, если / когда вы окажетесь в такой ситуации на своем Mac, вы сможете сбросить переменную среды PATH с помощью этого руководства. А затем восстановите функциональность терминала и повторно укажите пути к программам / сценариям bash, которые вы хотите запускать из любой точки файловой системы.

Часто задаваемые вопросы о сбросе переменной PATH на Mac

1. Как мне сбросить мою переменную PATH?

Сброс переменной PATH возможен либо через интерфейс командной строки, либо через графический интерфейс. Поэтому, в зависимости от ваших предпочтений, вы можете выбрать любой из этих методов. Выполните действия, описанные ранее в сообщении, чтобы узнать, как работают оба этих метода.

2. Какая переменная PATH используется по умолчанию в Mac?

В идеале файлы конфигурации или профиля оболочки содержат в качестве переменной PATH по умолчанию в Mac следующее: / usr / локальный / bin: / usr / bin: / bin: / usr / sbin: / sbin, чтобы вы могли выполнять различные программы или команды в терминале без указания их абсолютных путей.

3. Как мне исправить мою переменную окружения PATH?

В случае, если вы случайно испортили записи переменной среды PATH вашего Mac, вы можете исправить их, добавив записи PATH по умолчанию в файл конфигурации оболочки. В зависимости от того, как вам нравится выполнять операции на вашем Mac, вы можете сделать это с помощью графического интерфейса (Finder) или CLI (Терминал) подход.

4. Переменная PATH продолжает сбрасывать Mac?

Если переменная PATH продолжает сбрасываться на вашем Mac, это может быть связано с тем, что она не установлена ​​постоянно. Итак, вы должны отредактировать файл конфигурации оболочки вашей системы по умолчанию и добавить пути по умолчанию вместе с путем к программе / сценарию, которую вы хотите сделать доступной для него глобально.

Возможно, теперь очевидно, что изменение PATH нацелено на более продвинутых пользователей и разработчиков, которые используют терминал и проводят много времени в командной строке. Обычно пользователям Mac не нужно изменять, добавлять или иным образом корректировать это в OS X. Говоря об OS X, хотя это, очевидно, ориентировано на Mac, вы можете использовать этот же трюк, чтобы добавить PATH в свою оболочку в Linux, так как а также большинство других ароматов unix.

Добавление каталога в PATH

Самый простой способ добавить новый путь к переменной $ PATH (переменная среды) — с помощью команды export. В этом примере мы добавим «~ / opt / bin» пользователю PATH с экспортом:

export PATH = $ PATH: ~ / opt / bin

Вы можете запустить это непосредственно из командной строки, а затем проверить $ PATH с помощью эха, чтобы показать, что он был добавлен так:

echo $ PATH

Это должно возвращать что-то вроде следующего, обратите внимание на недавно добавленный каталог ~ / opt / bin в конце:

/ USR / бен: / бен: / USR / SBIN: / SBIN: / USR / местные / бен: / Users / osxdaily / Opt / бен

Добавить новый PATH в $ PATH в терминале OS X

Добавление нескольких путей к PATH

Подобно тому, как несколько путей могут быть сохранены и объединены в $ PATH в соответствии с их приоритетом поиска, вы также можете добавить новые пути таким же образом. Мы будем использовать тот же пример, что и раньше, но на этот раз также добавим каталог ~ / dev / bin:

export PATH = $ PATH: ~ / opt / bin: ~ / dev / bin

Настройка PATH в профиле оболочки

Имейте в виду, что для сохранения изменений в PATH вы захотите добавить их в файлы ~ / .profile, .zshrc или ~ / .bash_profile, в зависимости от используемой оболочки. Используйте свой любимый текстовый редактор, чтобы сделать это, будь то nano, emacs или vim. Если вы усложняетесь, рекомендуется добавить комментарии в .profile, чтобы все было легко сканироваться:

#Adding opt bin и dev bin для PATH для удовольствия
export PATH = $ PATH: ~ / opt / bin: ~ / dev / bin

Bash является оболочкой по умолчанию в OS X, но zsh, sh, ksh и tcsh также поставляются вместе с Mac, а смена оболочки OS X — очень простой процесс с chsh или в настройках Terminal и / или iTerm2.

Содержание

  1. Использование переменных среды в Терминале на Mac
  2. MacOS: Set / Change $PATH Variable Command
  3. macOS (OS X): Change your PATH environment variable
  4. Method #1: $HOME/.bash_profile file
  5. Method #2: /etc/paths.d directory
  6. Conclusion
  7. Как добавить новый путь к PATH в командной строке правильно
  8. Добавление каталога в PATH
  9. Добавление нескольких путей к PATH
  10. Настройка 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.

Источник

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:

  1. $HOME/.bash_profile file using export syntax.
  2. /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

  1. Use $HOME/.bash_profile file when you need to generate the PATH variable for a single user account.
  2. 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.

Источник

Как добавить новый путь к PATH в командной строке правильно

Возможно, теперь очевидно, что изменение PATH нацелено на более продвинутых пользователей и разработчиков, которые используют терминал и проводят много времени в командной строке. Обычно пользователям Mac не нужно изменять, добавлять или иным образом корректировать это в OS X. Говоря об OS X, хотя это, очевидно, ориентировано на Mac, вы можете использовать этот же трюк, чтобы добавить PATH в свою оболочку в Linux, так как а также большинство других ароматов unix.

Добавление каталога в PATH

Самый простой способ добавить новый путь к переменной $ PATH (переменная среды) — с помощью команды export. В этом примере мы добавим «

/ opt / bin» пользователю PATH с экспортом:

export PATH = $ PATH:

Вы можете запустить это непосредственно из командной строки, а затем проверить $ PATH с помощью эха, чтобы показать, что он был добавлен так:

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

/ opt / bin в конце:

/ USR / бен: / бен: / USR / SBIN: / SBIN: / USR / местные / бен: / Users / osxdaily / Opt / бен

Добавление нескольких путей к PATH

Подобно тому, как несколько путей могут быть сохранены и объединены в $ PATH в соответствии с их приоритетом поиска, вы также можете добавить новые пути таким же образом. Мы будем использовать тот же пример, что и раньше, но на этот раз также добавим каталог

export PATH = $ PATH:

Настройка PATH в профиле оболочки

Имейте в виду, что для сохранения изменений в PATH вы захотите добавить их в файлы

/ .profile, .zshrc или

/ .bash_profile, в зависимости от используемой оболочки. Используйте свой любимый текстовый редактор, чтобы сделать это, будь то nano, emacs или vim. Если вы усложняетесь, рекомендуется добавить комментарии в .profile, чтобы все было легко сканироваться:

#Adding opt bin и dev bin для PATH для удовольствия
export PATH = $ PATH:

Bash является оболочкой по умолчанию в OS X, но zsh, sh, ksh и tcsh также поставляются вместе с Mac, а смена оболочки OS X — очень простой процесс с chsh или в настройках Terminal и / или iTerm2.

Источник

Понравилась статья? Поделить с друзьями:
  • Как изменить patchwall
  • Как изменить readme github
  • Как изменить rdpwrap ini
  • Как изменить rdp файл через блокнот
  • Как изменить rcon пароль