How to set your $PATH variable in Linux

How to set your $PATH variable in Linux

Многие программы при запуске требуют повышения прав (значок щита у иконки), однако на самом деле для их нормальной работы прав администратора не требуется (например, вы вручную предоставили необходимые права пользователям на каталог программы в ProgramFiles и ветки реестра, которые используются программой). Соответственно, при запуске такой программы из-под простого пользователя, если на компьютере включен контроль учетных записей, появится запрос UAC и от пользователя потребует ввести пароль администратора. Чтобы обойти этот механизм многие просто отключают UAC или предоставляют пользователю права администратора на компьютере, добавляя его в группу локальных администраторов. Естественно, оба этих способа небезопасны.

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

Set ApplicationPath="C:\Program Files\MyApp\testapp.exe"
cmd /min /C "set __COMPAT_LAYER=RUNASINVOKER && start "" %ApplicationPath%"

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


cmd Windows администрирование Хауту


When you type a command into the command prompt in Linux, or in other Linux-like operating systems, all you’re doing is telling it to run a program. Even simple commands, like ls, mkdir, rm, and others are just small programs that usually live inside a directory on your computer called /usr/bin. There are other places on your system that commonly hold executable programs as well; some common ones include /usr/local/bin, /usr/local/sbin, and /usr/sbin. Which programs live where, and why, is beyond the scope of this article, but know that an executable program can live practically anywhere on your computer: it doesn’t have to be limited to one of these directories.

When you type a command into your Linux shell, it doesn’t look in every directory to see if there’s a program by that name. It only looks to the ones you specify. How does it know to look in the directories mentioned above? It’s simple: They are a part of an environment variable, called $PATH, which your shell checks in order to know where to look.

View your PATH

Sometimes, you may wish to install programs into other locations on your computer, but be able to execute them easily without specifying their exact location. You can do this easily by adding a directory to your $PATH. To see what’s in your $PATH right now, type this into a terminal:

echo $PATH

You’ll probably see the directories mentioned above, as well as perhaps some others, and they are all separated by colons. Now let’s add another directory to the list.

Set your PATH

Let’s say you wrote a little shell script called hello.sh and have it located in a directory called /place/with/the/file. This script provides some useful function to all of the files in your current directory, that you’d like to be able to execute no matter what directory you’re in.

export PATH=$PATH:/place/with/the/file

You should now be able to execute the script anywhere on your system by just typing in its name, without having to include the full path as you type it.

Set your PATH permanently

But what happens if you restart your computer or create a new terminal instance? Your addition to the path is gone! This is by design. The variable $PATH is set by your shell every time it launches, but you can set it so that it always includes your new path with every new shell you open. The exact way to do this depends on which shell you’re running.

Not sure which shell you’re running? If you’re using pretty much any common Linux distribution, and haven’t changed the defaults, chances are you’re running Bash. But you can confirm this with a simple command:

echo $0

For Bash, you simply need to add the line from above, export PATH=$PATH:/place/with/the/file, to the appropriate file that will be read when your shell launches. There are a few different places where you could conceivably set the variable name: potentially in a file called ~/.bash_profile, ~/.bashrc, or ~/.profile. The difference between these files is (primarily) when they get read by the shell. If you’re not sure where to put it, ~/.bashrc is a good choice.

For other shells, you’ll want to find the appropriate place to set a configuration at start time; ksh configuration is typically found in ~/.kshrc, zsh uses ~/.zshrc. Check your shell’s documentation to find what file it uses.

This is a simple answer, and there are more quirks and details worth learning. Like most everything in Linux, there is more than one way to do things, and you may find other answers which better meet the needs of your situation or the peculiarities of your Linux distribution. Happy hacking, and good luck, wherever your $PATH may take you.


Everything you do in the open source FreeDOS operating system is done from the command line. The command line begins with a prompt, which is the computer’s way of saying, “I’m ready. Give me something to do.” You can configure your prompt’s appearance, but by default, it’s:

C:\>

From the command line, you can do two things: Run an internal command or run a program. External commands are programs found in separate files in your FDOS directory, so running programs includes running external commands. It also means running the application software you use to do things with your computer. You can also run a batch file, but in that case, all you’re doing is running a series of commands or programs that are listed in the batch file.

Executable application files

FreeDOS can run three types of application files:

  1. COM is a file in machine language less than 64KB in size.
  2. EXE is a file in machine language that can be larger than 64KB. EXE files also have information at the beginning of the file telling DOS what type of file it is and how to load and run it.
  3. BAT is a batch file written with a text editor in ASCII text format containing FreeDOS commands that are executed in batch mode. This means each command is executed in sequence until the file ends.

If you enter an application name that FreeDOS does not recognize as either an internal command or a program, you get the error message Bad command or filename. If you see this error, it means one of three things:

  1. The name you gave is incorrect for some reason. Possibly you misspelled the file name, or maybe you’re using the wrong command name. Check the name and the spelling and try again.
  2. Maybe the program you are trying to run is not installed on the computer. Verify that it is installed.
  3. The file does exist, but FreeDOS doesn’t know where to find it.

The final item on this list is the subject of this article, and it’s referred to as the PATH. If you’re used to Linux or Unix already, you may already understand the concept of the PATH variable. If you’re new to the command line, the path is an important thing to get comfortable with.

The path

When you enter the name of an executable application file, FreeDOS has to find it. FreeDOS looks for the file in a specific hierarchy of locations:

  1. First, it looks in the active directory of the current drive (called the working directory). If you’re in the directory C:\FDOS, and you type in the name FOOBAR.EXE, FreeDOS looks in C:\FDOS for a file with that name. You don’t even need to type in the entire name. If you type in FOOBAR, FreeDOS looks for any executable file with that name, whether it’s FOOBAR.EXE, FOOBAR.COM, or FOOBAR.BAT. Should FreeDOS find a file matching that name, it runs it.
  2. If FreeDOS does not find a file with the name you’ve entered, it consults something called the PATH. This is a list of directories that DOS has been instructed to check whenever it cannot find a file in the current active directory.

You can see your computer’s path at any time by using the PATH command. Just type path at the FreeDOS prompt, and FreeDOS returns your path setting:

C:\>path
PATH=C:\FDOS\BIN

The first line is the prompt and the command, and the second line is what the computer returned. You can see that the first place DOS looks is FDOS\BIN, which is located on the C drive. If you want to change your path, you can enter a path command and the new path you want to use:

C:\>path=C:\HOME\BIN;C:\FDOS\BIN

In this example, I set my path to my personal BIN folder, which I keep in a custom directory called HOME, and then to FDOS\BIN. Now when you check your path:

C:\>path
PATH=C:\HOME\BIN;C:\FDOS\BIN

The path setting is processed in the order that directories are listed.

:/>  Команда для регистрации DLL в Windows не может быть найдена ни внутри, ни снаружи, так как ни команды Regsvr32, ни regsrv32 не распознаются

You may notice that some characters are lower case and some upper case. It really doesn’t matter which you use. FreeDOS is not case-sensitive and treats everything as an upper-case letter. Internally, FreeDOS uses all upper-case letters, which is why you see the output from your commands in upper case. If you type commands and file names in lower case, a converter automatically converts them to upper case, and they are executed.

Entering a new path replaces whatever the path was set to previously.

The autoexec. bat file

C:\>edit autoexec.bat

This line appears near the top:

SET PATH=%dosdir%\BIN

This line defines the value of the default path.

  1. Alt
  2. x

You can also use the keyboard shortcut Alt+X.

Using the full path

If you forget to include C:\FDOS\BIN in your path, you won’t have immediate access to any of the applications stored there because FreeDOS won’t know where to find them. For instance, imagine I set my path to my personal collection of applications:

C:\>path=C:\HOME\BIN

Applications built into the command line still work:

C:\cd HOME
C:\HOME>dir
ARTICLES
BIN
CHEATSHEETS
GAMES
DND

However, external commands fail:

C:HOME\ARTICLES>BZIP2 -c example.txt
Bad command or filename - "BZIP2"

You can always execute a command that you know is on your system but not in your path by providing the full path to the file:

C:HOME\ARTICLES>C:\FDOS\BIN\BZIP2 -c example.txt
C:HOME\ARTICLES>DIR
example.txb

You can execute applications from external media or other directories the same way.

FreeDOS path

Generally, you probably want to keep C:\PDOS\BIN in your path because it contains all the default applications distributed with FreeDOS.

Unless you change the path in AUTOEXEC.BAT, the default path is restored after a reboot.

Now that you know how to manage your path in FreeDOS, you can execute commands and maintain your working environment in whatever way works best for you.


The PATH Environment Variable

Understanding the PATH variable and adding commands to use in your terminal

PATH variable

Your computer (Mac or Linux, or a Unix-based system) has an environment variable called PATH, which contains a set of executable program directories that contain the executable programs.

Executable programs are basically the commands you can use in the shell.

These include the essential boot-stage or early-stage required binaries as well as other general system-wide commands.

In addition to the system-level binaries, executable programs can also include host specific program commands.

When you install a program or application on your Mac through the internet, the application will be available to execute using GUI, usually from the /Application directory.

In order to use the command line command to run the application, however, the executable file for the application must be saved to the PATH variable. In other words, you must add the directory of the executable program file for the application to the PATH variable in order to use the name of the executable file as the command to run it from the shell.

When you install an application through a package manager, such as Homebrew, it is symlinked to /usr/local/bin, which is usually included in PATH.

For other direct program installations, it is your job to either save the original executable file to the PATH variable directly, or symlink the executable file to a separate bin folder, which would be included in PATH.

Let’s take a look at how we can go about adding these local application commands to the PATH variable so that we can use their commands in our shell.

Adding to PATH

Export PATH=

This syntax prepends /path/to/app/executable/file/directory to the existing PATH variable.

  • export command allows all child processes to inherit the marked variable.
  • $PATH refers to the PATH variable value
  • assigning the path /path/to/app/executable/file/directory to the PATH variable with the trailing :$PATH essentially adds the path to the front of the existing PATH value with the separator :
  • You can also append the path to the existing PATH (add to the end) by instead using
    export PATH="$PATH:/path/to/app/executable/file/directory"

Path+=

path is another variable that is tied to the PATH variable, but it is an array. PATH and path are tied together, so changing either one will change the other.

  • however the variables’ value syntax are different:
  • Note the PATH is separated by : while path is separated by whitespace.
  • You can force the path variable to have only unique values by using typeset -U path command before path assignment. This will keep the path value clean by preventing duplicate directory names being added.

Here, the path/path/to/app/executable/file/directory will likely be a application bin directory starting from the /Applications directory.

  • For example, for Visual Studio Code, the path is:
/Applications/Visual Studio Code.app/Contents/Resources/app/bin
  • So, you would set:
export PATH="/Applications/Visual Studio Code.app/Contents/Resources/app/bin:$PATH"

This allows you to use the ‘code’ command (which is the name of the executable file) to run Visual Studio Code from the command line.

Symlinking the executable program file to a personal bin directory

Instead of adding each executable program file to the PATH separately, you can symlink the executable program file to a separate folder and add this folder to the PATH.

  • This separate folder could be a bin folder on your home directory: ~/bin.
  • You will have to create this in your home directory:
>> mkdir ~/bin

You can use ln command to symlink the executable file.

  • ln is a utility program that creates a new directory entry (a linked file), which has the same modes as the original file. The link ‘points’ to the original copy. How the link ‘points’ to the original file is the difference between a hard link and a symbolic link.
  • By default ln creates hard links, where any changes to the original file are effectively independent from the linked file.
  • Using the -s flag creates a symbolic link (symlink), which is a soft copy, allowing for the use of the referenced file when an operation is performed on the linked file.
>> ln -s "/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code" ~/bin

If you have the ~/bin directory added to the PATH variable, you just need to to symlink any executable program you want to add command for to the ~/bin directory.

This will make the organization of the PATH much cleaner and much easier to see what executable programs are included in the PATH.

References

  • https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard
  • https://askubuntu.com/questions/308045/differences-between-bin-sbin-usr-bin-usr-sbin-usr-local-bin-usr-local
  • https://stackoverflow.com/questions/11530090/adding-a-new-entry-to-the-path-variable-in-zsh
  • man ln

What are Environment Variables?

Environment variables hold values related to the current environment, like the Operating System or user sessions.

Path

One of the most well-known is called PATH on Windows, Linux and Mac OS X. It specifies the directories in which executable programs* are located on the machine that can be started without knowing and typing the whole path to the file on the command line. (Or in Windows, the Run dialog in the Start Menu or Win+R).

For example, typing calc (the .exe can be omitted) in the command line on Windows will start up the Windows Calculator.

* You can add support for file extensions other than .exe by editing %PATHEXT%.

Other

Other variables might tell programs what kind of terminal is used (TERM on Linux/Mac OS X), or, on Windows, where the Windows folder is located (e.g., %WINDIR% is C:\Windows).

Creating new environment variables

In Windows, Linux and Unix, it’s possible to create new environment variables, whose values are then made available to all programs upon launch.

You can use this when writing scripts or programs that are installed or deployed to multiple machines and need to reference values that are specific to these machines. While a similar effect can be achieved using program-specific configuration settings, it’s easier to do this using an environment variable if multiple programs need to access the same value.

:/>  9 ошибок при установке Windows 10 и способы их исправить - Лайфхакер

GUI

  1. Open Control Panel » System » Advanced » Environment Variables.

  2. %windir%\System32\rundll32.exe sysdm.cpl,EditEnvironmentVariables

    in the Run dialog.

  3. Right-click (My) Computer and click on Properties, or simply press Win+Break.

    • In XP click on Advanced » Environment Variables.
    • In Vista+ click on Advanced system settings » Environment Variables.
  4. There are many other ways of reaching the same place, such as by typing “environment variables” in the Start Menu/Screen search box and so on.

There is also Rapid Environment Editor, which helps setting and changing environment variables in Windows without the need to go deep into the system settings. Another open source program for Windows with which the path environment can be edited very conveniently is Path Editor.

Command Line

Format

Environment Variables in Windows are denoted with percent signs (%) surrounding the name:

%name%

echo

C:\>echo %USERPROFILE%
C:\Users\Daniel

set

To create/set a variable, use set varname=value:

C:\>set FunnyCatPictures=C:\Users\Daniel\Pictures\Funny Cat Pictures
C:\>set FunnyCatPicturesTwo=%USERPROFILE%\Pictures\Funny Cat Pictures 2

To append/add a variable, use set varname=value;%varname%:

C:\>set Penguins=C:\Linux
C:\>set Penguins=C:\Windows;%Penguins%
C:\>echo %Penguins%
C:\Windows;C:\Linux

Environment variables set in this way are available for (the rest of)
the duration of the Command Prompt process in which they are set,
and are available to processes that are started after the variables were set.

setx

To create/set a variable permanently, use setx varname "value":

C:\>setx FunnyCatPictures "C:\Users\Daniel\Pictures\Funny Cat Pictures"
[Restart CMD]
C:\>echo %FunnyCatPictures%
C:\Users\Daniel\Pictures\Funny Cat Pictures

Unlike set, there is no equals sign and the value should be enclosed in quotes if it contains any spaces. Note that variables may expand to a string with spaces (e.g., %PATH% becomes C:\Program Files), so it is best to include quotes around values that contain any variables.

You must manually add setx to versions of Windows earlier than Vista.
Windows XP Service Pack 2 Support Tools

List of Windows Environment Variables

Here is a list of default environment variables, which are built into Windows. Some examples are:
%WINDIR%, %SystemRoot%, %USERPROFILE%, and %APPDATA%.
Like most names in Windows, these are case-insensitive.

Unix derivatives (FreeBSD, GNU / Linux, OS X)

These files are regular shell scripts and can contain more than just environment variable declarations. To set an environment variable, use export. To show your currently defined environment variables in a terminal, run env.

The export command is a standard way to define variables. The syntax is very intuitive. The outcome is identical for these two lines, but the first alternative is preferable in case portability to pre-POSIX Bourne shell is necessary.

var=value; export var
export var=value

The C shell and its descendants use a completely different syntax; there, the command is setenv.

See the Linux documentation project, Path HOWTO for a more thorough discussion on this topic.

Perhaps contrary to common belief, OS X is more “Unix” than Linux. Additionally to the files already mentioned, $PATH can be modified in these files:

  • /etc/paths contains all default directories that are added to the path, like /bin and /usr/sbin.
  • Any file in /etc/paths.d — commonly used by installers to make the executable files they provide available from the shell without touching system-wide or user-specific configuration files. These files simply contain one path per line. e.g., /Programs/Mozilla/Calendar/bin.

External Links

Environment Variables in XP
Windows XP Service Pack 2 Support Tools (Includes setx)
Environment Variables in Windows Vista and Windows 7
Adding executables to the Run Dialog Box
Mac OSX Tips – Setting Environment Variables
TLDP: Path Howto

enter image description here

This is the proper way to edit environment variables in all post-UAC versions of Windows, not what is suggested in the majority of the answers above.


An alternative workaround is to use PowerShell features as described here
https://technet.microsoft.com/en-us/library/ff730964.aspx


Windows 10 Anniversary Update (version 1607) released August 2, 2016 finally fixed this bug.

Sometimes we need to tell Windows where to look for a particular executable file or script. Windows provides a means to do this through the Path Environment Variable. The Path Environment Variable essentially provides the OS with a list of directories to look in for a particular .exe or file when the simple name of the file is entered at the command prompt.

For example, the Notepad.exe application resides in the C:\Windows\system32 directory. However, if we wish to open the Notepad application via the Windows Command Line, we need only type:

Opening Notepad.exe From the Windows Command Line:
C:\Users\John> notepad

This works because the Path variable on Windows by default contains a list of directories where application files and scripts are likely to be located. Each directory in the list is separated by a semi-colon.

Similarly, there is another environment variable, PATHEXT which specifies a list of file extensions which might be found when searching for the proper file within the paths in the Path variable. This is why we are able to type simply “Notepad” at the command prompt, instead of Notepad.exe.

Once a file with a matching name is located, Windows attempts to match the file extension (if one is present), again in the order specified in the PATHEXT variable. If a match is found, the file is processed accordingly.

Adding a Directory to the User Path Variable from the Command Line

Now, in order to invoke the sqlite3.exe from the command line, we need to add the C:\SQLite directory to our PATH environment variable. We can do this from the command line by using the command:

The setx Command – Syntax:
C:\Users\John> setx "%path%;C:\SQLite"

We can examine the contents of the PATH variable by typing:

Output PATH Variable to the Console:
C:\Users\John> echo %PATH%

Which gives the output:

Results of Echo %PATH% Command:
C:\Users\John>echo %PATH%
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\Wind
owsPowerShell\v1.0\;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance
Toolkit\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files\
Microsoft SQL Server\110\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\1
10\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\Manage
mentStudio\;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Priv
ateAssemblies\;C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C:\Prog
ram Files (x86)\Common Files\Acronis\SnapAPI\;C:\Program Files (x86)\Windows Liv
e\Shared;C:\Program Files\Calibre2\;C:\Program Files\Microsoft\Web Platform Inst
aller\;C:\Users\John\AppData\Roaming\npm;C:\Program Files (x86)\nodejs\;C:\Progr
am Files (x86)\Microsoft SDKs\Windows Azure\CLI\wbin;C:\Program Files (x86)\GtkS
harp\2.12\bin;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\;C:\SQLite

Adding a Directory to the System Path Variable from the Command Line

Add a Directory the the System PATH Variable Using the /m Flag:
C:\Users\John> setx /m path "%path%;C:\SQLite"

Adding a Directory to the Path Variable from the GUI

Or, we can do this using the GUI by navigating to Control Panel => All Control Panel Items => System, and then selecting the “Advanced System Settings” link:

Locate Advanced System Settings in Control Panels:

Control PanelAll Control Panel ItemsSystem

Then locate the “Environment Variables” button:

Open Environment Variables:

System Properties

Editing Environment Variables:

Environment Variables

Adding a User Path Variable in the Windows GUI:

add-path-variable

Added Path Variable to User Environment Variables:

New Environment Variables

Removing Directories from the PATH Variable

Additional Resources and Items of Interest

Команда SET – работа с переменными среды Windows

SET

SET

SET переменная
SET PATH – отобразить значение переменной PATH
Для создания новой переменной, или изменения значения существующей, используется команда :

переменная – Имя переменной среды.
строка – Строка символов, присваиваемая указанной переменной.

SET MyName=Vasya – установить значение переменной MyName

SET path=C:\progs;%path% – изменить значение переменной PATH, добавив в начало строки C:\progs

Команда SET без параметров используется для вывода текущих значений переменных среды.

Кроме переменных, отображаемых в списке, при вызове команды SET, существуют и другие,
значения которых изменяется динамически:

%CD% – принимает значение текущего каталога.

%DATE% – принимает значение текущей даты.

%TIME% – принимает значение текущего времени.

%RANDOM% – значение случайного числа в диапазоне между 0 и 32767.

%ERRORLEVEL% – текущее значение ERRORLEVEL, специальной переменной, которая используется в качестве признака результата выполнения программы.

%CMDEXTVERSION% значение версии расширенной обработки команд CMD.EXE.

%CMDCMDLINE% – раскрывается в исходную командную строку, которая вызвала
командный процессор .

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

SET U – выведет значения всех переменных, имена которых начинаются с ‘U’.

Команда SET поддерживает два дополнительных ключа:

SET /A выражение

Ключ /A указывает, что строка справа от знака равенства является числовым
выражением, значение которого вычисляется. Обработчик выражений очень
прост и поддерживает следующие операции, перечисленные в порядке убывания
приоритета:

При использовании любых логических или двоичных операторов необходимо
заключить строку выражения в кавычки. Любые нечисловые строки в выражении
рассматриваются как имена переменных среды, значения которых преобразуются
в числовой вид перед использованием. Если переменная с указанным именем
не определена в системе, вместо нее подставляется нулевое значение. Это
позволяет выполнять арифметические операции со значениями переменных среды,
причем не нужно вводить знаки % для получения значений. Если команда
SET /A вызывается из командной строки, а не из пакетного файла, она выводит
окончательное значение выражения. Слева от любого оператора присваивания
должно стоять имя переменной среды. Числовые значения рассматриваются как
десятичные, если перед ними не стоит префикс:

:/>  Определить хост по IP-адресу и отправить эхо-запрос ICMP на имя целевого хоста или IP-адрес

0x – для шестнадцатеричных чисел
0 – для восьмеричных чисел.

Пример использования префиксов:

В данном командном файле значение переменной REZ вычисляется сложением числа
10, представленного в шестнадцатеричном виде ( 0xA ) и числа 10 , представленного в восьмеричном ( 012 ).

Ключ /P позволяет установить значение переменной для входной строки, введенной
пользователем. Показывает указанное приглашение promptString перед чтением
введенной строки. Приглашение promptString может быть пустым. Данный ключ позволяет организовать диалог с пользователем в командном файле:

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

переменная:строка1=строка2 – заменяет в принимаемом значении переменной строку1 на строку2

Следующий командный файл использует замену символа “точка” на символ “тире” в значении
переменной, соответствующем текущей дате:

Для выделения части значения, принимаемого переменной, используется следующая конструкция:

переменная:~x,y – где x – число пропускаемых символов от начала строки, а y – количество символов, используемых в качестве значения переменной.

Следующий пример использует отображение текущего времени без секунд и долей секунд (только первые 5 символов из стандартного значения переменной TIME):

Если значение y ( длина ) не указана, то используется оставшееся до конца строки
значение переменной. Если значение y отрицательно, то используется часть строки значения переменной от конца. Предыдущий пример можно изменить , указав, что в
принимаемом значении времени отбрасываются 6 символов от конца:

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

%PATH:~-10% – извлечет последние 10 символов переменной PATH

.
Нулевое значение можно не указывать, сохраняя формат подстановки:

%PATH:~0,-2% эквивалентно %PATH:~,-2%

При использовании переменных окружения в командных файлах существует определенное ограничение, связанное с тем фактом, что присваиваемое значение остается без изменения при его модификации внутри группы команд, задаваемой скобками, например в командах IF или FOR . Для обхода данного ограничения используется запуск командного процессора с параметром /V:ON и вместо знаков процента, для получения принимаемого переменной значения, используются восклицательные знаки. Кроме того, существует возможность использовать стандартный запуск командного процессора, но с локальным включением данного режима командой :

Разница в результатах использования значений переменных довольно наглядно
демонстрируется следующим командным файлом:

Значение переменной LIST внутри цикла изменено не будет. Для того, чтобы это произошло, командный файл нужно изменить следующим образом:


Весь список команд CMD Windows

Команда PATH используется для указания или просмотра путей поиска исполняемых файлов. Пути поиска представляют собой строки, определяющие перечень каталогов файловой системы, в которых находятся исполняемые файлы (файлы с расширением .bat, .cmd, .exe, .vbs и т.п. ), разделенные точкой с запятой ; Например, C:\windows;C:\windows\system32 – определяет пути поиска C:\windows и C:\windows\system32. Если вы в командной строке набираете program.exe без явного указания пути, то для запуска файла program.exe выполняется его поиск в текущем каталоге, и если он не найден, то в каталоге C:\windows, если и там не найден – в каталоге C:\windows\system32. Если же исполняемый файл будет в обоих каталогах, то выполнится запуск из того, что определен ранее – C:\windows. Значение переменной среды PATH содержит пути поиска исполняемых файлов определенный на данный момент времени.

Формат командной строки:

PATH ; – очистить путь поиска используемых файлов, ограничив его
текущим каталогом.

Команда PATH без параметров отображает текущий путь поиска.
В командную строку допускается включение переменной %PATH% , задающей прежний путь поиска.

path /? – отобразить подсказку по использованию команды.

path – отобразить пути поиска исполняемых файлов.

path %PATH%;C:\Scripts – добавить путь C:\Scripts в конец существующего списка каталогов для поиска исполняемых файлов.

path C:\scripts;%PATH% – добавить путь C:\Scripts в начало существующего списка каталогов для поиска исполняемых файлов.

При выполнении команды PATH, значение передаваемых ей параметров не анализируется и воспринимается как обычная строка символов, поэтому, например, трижды выполнив команду path C:\scripts;%PATH% вы создадите 3 записи для пути C:\Scripts. Значение переменной PATH, измененное командой действует только на момент текущего сеанса командной строки. Для постоянного изменения системных и пользовательских переменных среды, в том числе, и путей поиска, используется команда SetX .
В постоянно действующих путях поиска не стоит указывать каталоги сменных носителей (дискет, CD/DVD, карты памяти и т.п.)


Весь список команд CMD Windows

The simple stuff

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

depending on whether you want to add ~/opt/bin at the end (to be searched after all other directories, in case there is a program by the same name in multiple directories) or at the beginning (to be searched before all other directories).

You can add multiple entries at the same time. PATH=$PATH:~/opt/bin:~/opt/node/bin or variations on the ordering work just fine. Don’t put export at the beginning of the line as it has additional complications (see below under “Notes on shells other than bash”).

If your PATH gets built by many different components, you might end up with duplicate entries. See How to add home directory path to be discovered by Unix which command? and Remove duplicate $PATH entries with awk command to avoid adding duplicates or remove them.

Some distributions automatically put ~/bin in your PATH if it exists, by the way.

Where to put it

Put the line to modify PATH in ~/.profile, or in ~/.bash_profile or if that’s what you have. (If your login shell is zsh and not bash, put it in ~/.zprofile instead.)

The profile file is read by login shells, so it will only take effect the next time you log in. (Some systems configure terminals to read a login shell; in that case you can start a new terminal window, but the setting will take effect only for programs started via a terminal, and how to set PATH for all programs depends on the system.)

Note that ~/.bash_rc is not read by any program, and ~/.bashrc is the configuration file of interactive instances of bash. You should not define environment variables in ~/.bashrc. The right place to define environment variables such as PATH is ~/.profile (or ~/.bash_profile if you don’t care about shells other than bash). See What’s the difference between them and which one should I use?

Don’t put it in /etc/environment or ~/.pam_environment: these are not shell files, you can’t use substitutions like $PATH in there. In these files, you can only override a variable, not add to it.

Potential complications in some system scripts

You don’t need export if the variable is already in the environment: any change of the value of the variable is reflected in the environment.¹ PATH is pretty much always in the environment; all unix systems set it very early on (usually in the very first process, in fact).

At login time, you can rely on PATH being already in the environment, and already containing some system directories. If you’re writing a script that may be executed early while setting up some kind of virtual environment, you may need to ensure that PATH is non-empty and exported: if PATH is still unset, then something like PATH=$PATH:/some/directory would set PATH to :/some/directory, and the empty component at the beginning means the current directory (like .:/some/directory).

if [ -z "${PATH-}" ]; then export PATH=/usr/local/bin:/usr/bin:/bin; fi

Notes on shells other than bash

In bash, ksh and zsh, export is special syntax, and both PATH=~/opt/bin:$PATH and export PATH=~/opt/bin:$PATH do the right thing even. In other Bourne/POSIX-style shells such as dash (which is /bin/sh on many systems), export is parsed as an ordinary command, which implies two differences:

  • ~ is only parsed at the beginning of a word, except in assignments (see How to add home directory path to be discovered by Unix which command? for details);
  • $PATH outside double quotes breaks if PATH contains whitespace or \[*?.

¹ This wasn’t true in Bourne shells (as in the actual Bourne shell, not modern POSIX-style shells), but you’re highly unlikely to encounter such old shells these days.