Linux app to path

Get path to application?

How can a user determine the path to an application being showed in launcher?

This is meant for non-programmers or experts, so terminal commands are not really suited for them. Why: we need to make our users able to drag files/folders on our applications, a standard OS feature entirely missing in Ubuntu.

3 Answers 3

Go to /usr/share/applications or

/.local/share/applications , right-click the application icon and click on «Properties».

I do not see a reason why a person who can’t run a command in terminal would need a path.

In 18.04 and later launch an application by clicking on its icon in the Dash which is accessed by clicking the 9 dots icon in the lower left corner of the dock. Launch the System Monitor and make a note of the exact spelling of the name of the application that you just opened. Open the terminal and type:

It takes only a few seconds to get the path to an application in Ubuntu 14.04 and later. Search for the application in the Dash and then drag the application’s icon into the terminal. The application’s full path will be shown in the terminal automatically. Dragging the icon into the terminal will also show the path to any file, folder, archive or anything else that has an icon.

In Ubuntu 20.04 and later drag and drop of files or directories doesn’t work from the desktop, but does work in other locations including dragging from the desktop in Files file manager.

Источник

Переменная 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 и как добавлять к её значению новые пути поиска исполняемых и связанных с ними файлов. Как видите, всё делается достаточно просто. Таким образом вы можете добавить столько папок для поиска и хранения исполняемых файлов, сколько вам требуется.

Читайте также:  Crypt32 dll windows 2003

Источник

How to set your $PATH variable in Linux

Telling your Linux shell where to look for executable files is easy, and something everyone should be able to do.

Subscribe now

Get the highlights in your inbox every week.

Being able to edit your $PATH is an important skill for any beginning POSIX user, whether you use Linux, BSD, or macOS.

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:

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.

Simply add /place/with/the/file to the $PATH variable with the following command:

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:

That’s the «echo» command followed by a dollar sign ($) and a zero. $0 represents the zeroth segment of a command (in the command echo $0, the word «echo» therefore maps to $1), or in other words, the thing running your command. Usually this is the Bash shell, although there are others, including Dash, Zsh, Tcsh, Ksh, and Fish.

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

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

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

Читайте также:  Windows 10 настройка языка при входе

This article was originally published in June 2017 and has been updated with additional information by the editor.

Источник

How to correctly add a path to PATH?

I’m wondering where a new path has to be added to the PATH environment variable. I know this can be accomplished by editing .bashrc (for example), but it’s not clear how to do this.

12 Answers 12

The simple stuff

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

/.bash_profile if that’s what you have.

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

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

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 \[*? .
  • So in shells like dash, export PATH=

    /opt/bin:$PATH sets PATH to the literal string

    /opt/bin/: followed by the value of PATH up to the first space. PATH=

    /opt/bin:$PATH (a bare assignment) doesn’t require quotes and does the right thing. If you want to use export in a portable script, you need to write export PATH=»$HOME/opt/bin:$PATH» , or PATH=

    /opt/bin:$PATH; export PATH (or PATH=$HOME/opt/bin:$PATH; export PATH for portability to even the Bourne shell that didn’t accept export var=value and didn’t do tilde expansion).

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

    /.bashrc«, but unfortunately 100% of the programs that I have installed on my system that modify the path (FZF and Rust’s Cargo) modify the path in .bashrc . I assume because FZF is written in Rust too it’s following the pattern of Rust.

    Either way works, but they don’t do the same thing: the elements of PATH are checked left to right. In your first example, executables in

    Читайте также:  Активация windows с помощью ключа продукта

    /opt/bin will have precedence over those installed, for example, in /usr/bin , which may or may not be what you want.

    In particular, from a safety point of view, it is dangerous to add paths to the front, because if someone can gain write access to your

    /opt/bin , they can put, for example, a different ls in there, which you’d then probably use instead of /bin/ls without noticing. Now imagine the same for ssh or your browser or choice. (The same goes triply for putting . in your path.)

    The bullet-proof way of Appending/Prepending

    Try not using

    Why? There are a lot of considerations involved in the choice of appending versus prepending. Many of them are covered in other answers, so I will not repeat them here.

    An important point is that, even if system scripts do not use this (I wonder why) *1 , the bullet-proof way to add a path (e.g.,

    /opt/bin ) to the PATH environment variable is

    for appending (instead of PATH=»$PATH:

    for prepending (instead of PATH=»

    This avoids the spurious leading/trailing colon when $PATH is initially empty, which can have undesired side effects and can become a nightmare, elusive to find (this answer briefly deals with the case the awk -way).

    If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.

    1. nothing, if PATH is null or unset,
    2. $: , if PATH is set.

    Note: This is for bash.

    *1 I have just found that scripts like `devtoolset-6/enable` actually use this,

    I’m confused by question 2 (since removed from the question since it was due to an unrelated issue):

    What’s a workable way to append more paths on different lines? Initially I thought this could do the trick:

    but it doesn’t because the second assignment doesn’t only append

    /opt/node/bin , but also the whole PATH previously assigned.

    This is a possible workaround:

    but for readability I’d prefer to have one assignment for one path.

    that’s all that will be in your PATH. PATH is just an environment variable, and if you want to add to the PATH, you have to rebuild the variable with exactly the contents you want. That is, what you give as an example to question 2 is exactly what you want to do, unless I’m totally missing the point of the question.

    I use both forms in my code. I have a generic profile that I install on every machine I work on that looks like this, to accommodate for potentially-missing directories:

    Linux determines the executable search path with the $PATH environment variable. To add directory /data/myscripts to the beginning of the $PATH environment variable, use the following:

    To add that directory to the end of the path, use the following command:

    But the preceding are not sufficient because when you set an environment variable inside a script, that change is effective only within the script. There are only two ways around this limitation:

    • If within the script, you export the environment variable it is effective within any programs called by the script. Note that it is not effective within the program that called the script.
    • If the program that calls the script does so by inclusion instead of calling, any environment changes in the script are effective within the calling program. Such inclusion can be done with the dot command or the source command.

    Inclusion basically incorporates the «called» script in the «calling» script. It’s like a #include in C. So it’s effective inside the «calling» script or program. But of course, it’s not effective in any programs or scripts called by the calling program. To make it effective all the way down the call chain, you must follow the setting of the environment variable with an export command.

    As an example, the bash shell program incorporates the contents of file .bash_profile by inclusion. Place the following 2 lines in .bash_profile:

    effectively puts those 2 lines of code in the bash program. So within bash, the $PATH variable includes $HOME/myscript.sh , and because of the export statement, any programs called by bash have the altered $PATH variable. And because any programs you run from a bash prompt are called by bash, the new path is in force for anything you run from the bash prompt.

    The bottom line is that to add a new directory to the path, you must append or prepend the directory to the $PATH environment variable within a script included in the shell, and you must export the $PATH environment variable.

    Источник

    Оцените статью