- Переменная PATH в Linux
- Переменная PATH в Linux
- Выводы
- How to find application’s path from command line?
- 5 Answers 5
- How to get full path name of a Linux command
- 5 Answers 5
- How do I get the path of a process in Unix / Linux
- 11 Answers 11
- How do I get the directory that a program is running from?
- 24 Answers 24
Переменная PATH в Linux
Когда вы запускаете программу из терминала или скрипта, то обычно пишете только имя файла программы. Однако, ОС Linux спроектирована так, что исполняемые и связанные с ними файлы программ распределяются по различным специализированным каталогам. Например, библиотеки устанавливаются в /lib или /usr/lib, конфигурационные файлы в /etc, а исполняемые файлы в /sbin/, /usr/bin или /bin.
Таких местоположений несколько. Откуда операционная система знает где искать требуемую программу или её компонент? Всё просто — для этого используется переменная PATH. Эта переменная позволяет существенно сократить длину набираемых команд в терминале или в скрипте, освобождая от необходимости каждый раз указывать полные пути к требуемым файлам. В этой статье мы разберёмся зачем нужна переменная PATH Linux, а также как добавить к её значению имена своих пользовательских каталогов.
Переменная PATH в Linux
Для того, чтобы посмотреть содержимое переменной PATH в Linux, выполните в терминале команду:
На экране появится перечень папок, разделённых двоеточием. Алгоритм поиска пути к требуемой программе при её запуске довольно прост. Сначала ОС ищет исполняемый файл с заданным именем в текущей папке. Если находит, запускает на выполнение, если нет, проверяет каталоги, перечисленные в переменной PATH, в установленном там порядке. Таким образом, добавив свои папки к содержимому этой переменной, вы добавляете новые места размещения исполняемых и связанных с ними файлов.
Для того, чтобы добавить новый путь к переменной PATH, можно воспользоваться командой export. Например, давайте добавим к значению переменной PATH папку/opt/local/bin. Для того, чтобы не перезаписать имеющееся значение переменной PATH новым, нужно именно добавить (дописать) это новое значение к уже имеющемуся, не забыв о разделителе-двоеточии:
Теперь мы можем убедиться, что в переменной PATH содержится также и имя этой, добавленной нами, папки:
Вы уже знаете как в Linux добавить имя требуемой папки в переменную PATH, но есть одна проблема — после перезагрузки компьютера или открытия нового сеанса терминала все изменения пропадут, ваша переменная PATH будет иметь то же значение, что и раньше. Для того, чтобы этого не произошло, нужно закрепить новое текущее значение переменной PATH в конфигурационном системном файле.
В ОС Ubuntu значение переменной PATH содержится в файле /etc/environment, в некоторых других дистрибутивах её также можно найти и в файле /etc/profile. Вы можете открыть файл /etc/environment и вручную дописать туда нужное значение:
sudo vi /etc/environment
Можно поступить и иначе. Содержимое файла .bashrc выполняется при каждом запуске оболочки Bash. Если добавить в конец файла команду export, то для каждой загружаемой оболочки будет автоматически выполняться добавление имени требуемой папки в переменную PATH, но только для текущего пользователя:
Выводы
В этой статье мы рассмотрели вопрос о том, зачем нужна переменная окружения PATH в Linux и как добавлять к её значению новые пути поиска исполняемых и связанных с ними файлов. Как видите, всё делается достаточно просто. Таким образом вы можете добавить столько папок для поиска и хранения исполняемых файлов, сколько вам требуется.
Источник
How to find application’s path from command line?
For example, I have git installed on my system. But I don’t remember where I installed it, so which command is fit to find this out?
5 Answers 5
If it is in your path, then you can run either type git or which git . The which command has had problems getting the proper path (confusion between environment and dot files). For type , you can get just the path with the -p argument.
If it is not in your path, then it’s best to look for it with locate -b git It will find anything named ‘git’. It’ll be a long list, so might be good to qualify it with locate -b git | fgrep -w bin .
The POSIX standard way to do this is command -v git . All UNIX-like systems should support this.
whereis git and you get the path to the command.
that is just if the git is in you PATH variable, in case you have installed it not through you package manager, it is more complex and you should use the find or locate commands.
The other answers here seem to be largely geared towards modern versions of Linux, so if you happen to use git on an OS that doesn’t have locate , whereis , which , or apropos (like Solaris, HPUX, etc), then there is always the old standby find .
One some older versions of the systems listed above, you may need a -print option supplied to find .
Источник
How to get full path name of a Linux command
I want to find out the file path of commands in Linux e.g., ls has file path as /bin/ls . How can I find out the exact path of some commands?
5 Answers 5
As pointed out, which
would do it. You could also try:
This will list all the paths that contains progName . I.e whereis -b gcc on my machine returns:
you can use which , it give you path of command:
you can use type :
You can use the which command. In case of a command in your $PATH it will show you the full path:
And it will also show details about aliases:
Yes you can find it with which command
You did not specify, which shell you are going to use, but I strongly recommend using which , as it does not necessarily do, what you expect. Here two examples, where the result possibly is not what you expect:
(1) Example with bash, and the command echo :
would output /usr/bin/echo , but if you use the echo command in your bash script, /usr/bin/echo is not executed. Instead, the builtin command echo is executed, which is similar, but not identical in behaviour.
(2) Example with zsh, and the command which :
would output the message which: shell built-in command (which is correct, but certainly not a file path, as you requested), while
would output the file path /usr/bin/which , but (as in the bash example) this is not what’s getting executed when you just type which .
There are cases, when you know for sure (because you know your application), that which will produce the right result, but beware that as soon as builtin-commands, aliases and shell functions are involved, you need first to decide how you want to handle those cases, and then choose the appropriate tools depending on the kind of shell which you are using.
Источник
How do I get the path of a process in Unix / Linux
In Windows environment there is an API to obtain the path which is running a process. Is there something similar in Unix / Linux?
Or is there some other way to do that in these environments?
11 Answers 11
On Linux, the symlink /proc/
/exe has the path of the executable. Use the command readlink -f /proc/
/exe to get the value.
On AIX, this file does not exist. You could compare cksum and cksum /proc/
You can find the exe easily by these ways, just try it yourself.
gave me the location of the symbolic link so I could find the logs and stop the process in proper way.
| grep -m 1 txt , as the required process path info seems to be in the first line with txt , and not in the cwd line? (Applies on macOS and Ubuntu as of date of posting.)
A little bit late, but all the answers were specific to linux.
If you need also unix, then you need this:
EDITED: Fixed the bug reported by Mark lakata.
Replace 786 with your PID or process name.
This command will fetch the process path from where it is executing.
In Linux every process has its own folder in /proc . So you could use getpid() to get the pid of the running process and then join it with the path /proc to get the folder you hopefully need.
Here’s a short example in Python:
Here’s the example in ANSI C as well:
Compile it with:
There’s no «guaranteed to work anywhere» method.
Step 1 is to check argv[0], if the program was started by its full path, this would (usually) have the full path. If it was started by a relative path, the same holds (though this requires getting teh current working directory, using getcwd().
Step 2, if none of the above holds, is to get the name of the program, then get the name of the program from argv[0], then get the user’s PATH from the environment and go through that to see if there’s a suitable executable binary with the same name.
Note that argv[0] is set by the process that execs the program, so it is not 100% reliable.
The below command search for the name of the process in the running process list,and redirect the pid to pwdx command to find the location of the process.
Replace «abc» with your specific pattern.
Alternatively, if you could configure it as a function in .bashrc, you may find in handy to use if you need this to be used frequently.
Hope this helps someone sometime.
thanks : Kiwy
with AIX:
You can also get the path on GNU/Linux with (not thoroughly tested):
If you want the directory of the executable for perhaps changing the working directory to the process’s directory (for media/data/etc), you need to drop everything after the last /:
Источник
How do I get the directory that a program is running from?
Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the current working directory. (Please don’t suggest libraries unless they’re standard ones like clib or STL.)
(If there’s no platform/filesystem-agnostic method, suggestions that work in Windows and Linux for specific filesystems are welcome too.)
.exe file) is located, and the ‘current working directory’ is the directory, that is autocompleted if the program uses relative paths?
24 Answers 24
Here’s code to get the full path to the executing app:
If you fetch the current directory when your program first starts, then you effectively have the directory your program was started from. Store the value in a variable and refer to it later in your program. This is distinct from the directory that holds the current executable program file. It isn’t necessarily the same directory; if someone runs the program from a command prompt, then the program is being run from the command prompt’s current working directory even though the program file lives elsewhere.
getcwd is a POSIX function and supported out of the box by all POSIX compliant platforms. You would not have to do anything special (apart from incliding the right headers unistd.h on Unix and direct.h on windows).
Since you are creating a C program it will link with the default c run time library which is linked to by ALL processes in the system (specially crafted exceptions avoided) and it will include this function by default. The CRT is never considered an external library because that provides the basic standard compliant interface to the OS.
On windows getcwd function has been deprecated in favour of _getcwd. I think you could use it in this fashion.
On windows:
On Linux:
On HP-UX:
If you want a standard way without libraries: No. The whole concept of a directory is not included in the standard.
If you agree that some (portable) dependency on a near-standard lib is okay: Use Boost’s filesystem library and ask for the initial_path().
IMHO that’s as close as you can get, with good karma (Boost is a well-established high quality set of libraries)
I know it is very late at the day to throw an answer at this one but I found that none of the answers were as useful to me as my own solution. A very simple way to get the path from your CWD to your bin folder is like this:
You can now just use this as a base for your relative path. So for example I have this directory structure:
and I want to compile my source code to bin and write a log to test I can just add this line to my code.
I have tried this approach on Linux using full path, alias etc. and it works just fine.
If you are on windows you should use a ‘\’ as the file separator not ‘/’. You will have to escape this too for example:
I think this should work but haven’t tested, so comment would be appreciated if it works or a fix if not.
Filesystem TS is now a standard ( and supported by gcc 5.3+ and clang 3.9+ ), so you can use current_path() function from it:
In gcc (5.3+) to include Filesystem you need to use:
and link your code with -lstdc++fs flag.
If you want to use Filesystem with Microsoft Visual Studio, then read this.
On Windows the simplest way is to use the _get_pgmptr function in stdlib.h to get a pointer to a string which represents the absolute path to the executable, including the executables name.
No, there’s no standard way. I believe that the C/C++ standards don’t even consider the existence of directories (or other file system organizations).
On Windows the GetModuleFileName() will return the full path to the executable file of the current process when the hModule parameter is set to NULL. I can’t help with Linux.
Also you should clarify whether you want the current directory or the directory that the program image/executable resides. As it stands your question is a little ambiguous on this point.
Maybe concatenate the current working directory with argv[0]? I’m not sure if that would work in Windows but it works in linux.
When run, it outputs:
/Desktop$ ./test
/home/jeremy/Desktop/./test
For Win32 GetCurrentDirectory should do the trick.
You can not use argv[0] for that purpose, usually it does contain full path to the executable, but not nessesarily — process could be created with arbitrary value in the field.
Also mind you, the current directory and the directory with the executable are two different things, so getcwd() won’t help you either.
On Windows use GetModuleFileName(), on Linux read /dev/proc/procID/.. files.
Just my two cents, but doesn’t the following code portably work in C++17?
Seems to work for me on Linux at least.
Based on the previous idea, I now have:
And initialization trick in main() :
Thanks @Sam Redway for the argv[0] idea. And of course, I understand that C++17 was not around for many years when the OP asked the question.
Just to belatedly pile on here.
there is no standard solution, because the languages are agnostic of underlying file systems, so as others have said, the concept of a directory based file system is outside the scope of the c / c++ languages.
on top of that, you want not the current working directory, but the directory the program is running in, which must take into account how the program got to where it is — ie was it spawned as a new process via a fork, etc. To get the directory a program is running in, as the solutions have demonstrated, requires that you get that information from the process control structures of the operating system in question, which is the only authority on this question. Thus, by definition, its an OS specific solution.
For Windows system at console you can use system( dir ) command. And console gives you information about directory and etc. Read about the dir command at cmd . But for Unix-like systems, I don’t know. If this command is run, read bash command. ls does not display directory.
Works with starting from C++11, using experimental filesystem, and C++14-C++17 as well using official filesystem.
For relative paths, here’s what I did. I am aware of the age of this question, I simply want to contribute a simpler answer that works in the majority of cases:
Say you have a path like this:
For some reason, Linux-built executables made in eclipse work fine with this. However, windows gets very confused if given a path like this to work with!
As stated above there are several ways to get the current path to the executable, but the easiest way I find works a charm in the majority of cases is appending this to the FRONT of your path:
Just adding «./» should get you sorted! 🙂 Then you can start loading from whatever directory you wish, so long as it is with the executable itself.
EDIT: This won’t work if you try to launch the executable from code::blocks if that’s the development environment being used, as for some reason, code::blocks doesn’t load stuff right. 😀
EDIT2: Some new things I have found is that if you specify a static path like this one in your code (Assuming Example.data is something you need to load):
If you then launch your app from the actual directory (or in Windows, you make a shortcut, and set the working dir to your app dir) then it will work like that. Keep this in mind when debugging issues related to missing resource/file paths. (Especially in IDEs that set the wrong working dir when launching a build exe from the IDE)
Источник