dylnmc
dylnmc

Reputation: 4010

Why use $PATH and what is it

I'm sort of new to programming (not really, but I'm still learning - aren't we all?). Although I know Java and Python and sort of know C, C++, JS, C#, HTML, CSS, etc. (and I can navigate pretty well in the terminal), I am not familiar with what $PATH is in the terminal.

I've been using the Linux terminal and Mac terminal much more frequently than I used to (if I even did at all two years ago), and I know for python, it wants you to "export" its path like PATH=\path\to\python\bin:${PATH}\ export PATH. However, I don't even know what it does. I tried to find out, but all I could find were people saying "export this path and export that one."

So, what is it and why use it? I understand that (if you do it for Python), it basically makes 'python' (or 'python2' or 'python3') a variable, but I just don't understand the concept of what it is.

Upvotes: 2

Views: 1605

Answers (1)

andrewdotn
andrewdotn

Reputation: 34803

man bash describes it as:

PATH

The search path for commands. It is a colon-separated list of directories in which the shell looks for commands (see COMMAND EXECUTION below). A zero-length (null) directory name in the value of PATH indicates the current directory. A null directory name may appear as two adjacent colons, or as an initial or trailing colon. The default path is system-dependent, and is set by the administrator who installs bash. A common value is /usr/gnu/bin:/usr/local/bin:/usr/ucb:/bin:/usr/bin'.

When you run a command, like python, the operating system tries to find the python program in the list of directories stored in PATH.

Suppose your PATH is /usr/local/bin:/foo:/bar:/baz:/usr/bin. When you try to run the python comamnd, the operating system will look for an executable named python in those directories in order. On Linux, you can watch it do this with the strace command:

$ PATH=/usr/local/bin:/foo:/bar:/baz:/usr/bin strace -f /bin/bash -c 'python --version' 2>&1 | grep 'stat.*python'
stat("/usr/local/bin/python", 0x7fff98b63d00) = -1 ENOENT (No such file or directory)
stat("/foo/python", 0x7fff98b63d00)     = -1 ENOENT (No such file or directory)
stat("/bar/python", 0x7fff98b63d00)     = -1 ENOENT (No such file or directory)
stat("/baz/python", 0x7fff98b63d00)     = -1 ENOENT (No such file or directory)
stat("/usr/bin/python", {st_mode=S_IFREG|0755, st_size=4864, ...}) = 0

As soon as python is found in /usr/bin/python, the search stops, and the program runs.

Upvotes: 5

Related Questions