Add to the path mac os

Добавить переменную в $PATH macOS

Если скитание по интернету не дают вам ответа, как добавить переменную в $PATH macOS, то на сайте Я Знаю! Вы найдете простое решение!

Новая переменная $PATH macOS
для текущего пользователя

Для того чтобы раз и навсегда добавить новую переменную в $PATH macOS для текущего пользователя необходимо выполнить несложные действия в терминале.

Найдите в меню Launchpad приложение «Терминал» и запустите его. Введите команду для перехода в домашний каталог:

  • После чего приступите к редактированию файла .bash_profile:
  • Добавьте ваш путь к команде или скрипту:
  • Сохраните изменения с помощью нескольких комбинации клавиш
    • CTRL O
    • CTRL X

Полностью закройте приложение Терминал и снова запустите его, проверьте добавилась ли ваша новая переменная в $PATH:

Новая переменная $PATH macOS
для всех пользователей

Найдите в меню Launchpad приложение «Терминал» и запустите его, введите команду:

Добавьте путь к команде или скрипту:

  • Сохраните изменения с помощью нескольких комбинации клавиш
    • CTRL O
    • CTRL X
  • Проверьте наличие новой переменной:

Вот и все! Теперь вы знаете как добавить переменную в $PATH macOS!

Источник

How to Add a New Path to PATH at Command Line the Right Way

The user path is the series of directories that command line programs are searched in order to run. For example, if you type ‘iostat’ into the terminal, then iostat will be run from /usr/sbin because “/usr/sbin” is part of your $PATH. Accordingly, users who frequently use the command line may need to adjust or add new paths to their terminal so that commands can execute properly.

Perhaps obvious by now, modifying the PATH is aimed at more advanced users and developers who are using the Terminal and spending a lot of time at the command line. Average Mac users typically have no need to change, add, or otherwise adjust this in Mac OS X. Speaking of Mac OS X, while this is obviously Mac centric, you can use this same trick to add a PATH to your shell in Linux too, as well as most other unix flavors.

Before getting started, you might want to see the existing $PATH just in case you mess something up, that way you can easily restore to it by exporting using the same commands. To check the current $PATH simply type: “echo $PATH”

Adding a Directory to PATH

The easiest way to add a new path to $PATH (the environment variable) is with the export command. In this example we’ll add “

/opt/bin” to the user PATH with export:

You can run that directly from the command line, then check the $PATH with echo to show that it has been added like so:

This should return something like the following, note the newly added

/opt/bin directory at the end:

How to Add Multiple Paths to PATH

Just as multiple paths can be stored and strung together in $PATH in accordance to their search priority, you can also add new paths this way as well. We’ll use the same example as before, but this time also add the

Setting PATH in Shell Profile

Keep in mind that for changes to PATH to persist, you’ll want to add them into

/.profile, .zshrc, or

/.bash_profile, depending on which shell you use. Use your favorite text editor to do that, whether it’s nano, emacs, or vim. If you’re getting complicated, it’s a good idea to add comments to the .profile to keep things easily scannable:

#Adding opt bin and dev bin to PATH for fun
export PATH=$PATH:

Bash is the default shell in many versions of Mac OS X, but zsh is the default in later modern releases, and of course there are other shells like sh, ksh, and tcsh are also bundled with the Mac. Changing the Mac OS X shell is a very easy process either with chsh, or within Terminal and/or iTerm2 preferences.

Источник

Переход напрямую к определенной папке на Mac

Можно воспользоваться меню «Переход» для мгновенного перехода к нужной папке — например, папке «Документы» или другой недавно открытой папке. Если точное имя и расположение папки известны, ее можно открыть, введя путь к ней.

Читайте также:  Команда выключить сервер linux

Спросите Siri. Произнесите, например, «Открой домашнюю папку». Узнайте, как спросить Siri.

Переход к папке из списка в меню «Переход»

В Finder на Mac нажмите меню «Переход» в строке меню.

Выберите один из следующих вариантов.

На уровень выше: Выберите этот вариант, чтобы открыть вышестоящую папку для текущего окна. Например, если Вы находитесь в папке «Загрузки», этот вариант позволит открыть Вашу папку пользователя.

«Недавние», «Документы» или другие папки из списка. Выберите папку из списка.

Недавно использованные папки. Выберите папку из подменю. Чтобы изменить количество недавно использованных папок, отображаемых в списке, выберите меню Apple

> «Системные настройки», затем нажмите «Основные». Нажмите всплывающее меню «Недавно использованные объекты», затем выберите число.

Совет. Чтобы перейти в папку «Библиотека» в домашней папке пользователя, удерживайте нажатой клавишу Option и выберите «Библиотека».

Переход к папке с помощью ввода пути к ней

В Finder на Mac выберите «Переход» > «Переход к папке».

Введите имя пути папки (например, /Библиотеки/Fonts/ или

/Pictures/), затем нажмите «Переход».

Косая черта (/) в начале имени пути означает, что начальная точка является верхним уровнем структуры папок Вашего компьютера.

Косая черта в конце означает, что это путь к папке, а не к файлу.

) указывает на Вашу папку пользователя. Большинство Ваших личных папок, таких как «Документы», «Музыка» и «Изображения» находится в Вашей папке пользователя.

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

Источник

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)

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:

Читайте также:  Расшаренная папка windows 10 не видна

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.

Источник

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.

Источник

Читайте также:  Папка мои документы windows 10 не перемещается
Оцените статью