Unix 标准目录放置自定义可执行文件或脚本?

如果我有一个自定义的 shell 脚本或程序,我自己创建或从网上下载,我想能够执行这从 CLI,有没有标准的位置把它放在 Linux/Unix 目录结构?

/usr/bin ?
/usr/local/bin ?
/usr/lib ?
/usr/sbin ?
/bin ?
/sbin ?
/var ?

我通常把它放在我的 ~/bin目录下,并添加到 PATH,但它似乎不干净。每次我下载一个新程序,我必须把它再次添加到 PATH。

45136 次浏览

/usr/local/bin exists precisely for this purpose: for system-wide installation. For your own private use, ~/bin is the de facto standard.

If you want to keep each binary in its own subdirectory, you can do that, and add a symlink to a directory already in your PATH. So, for example:

curl -o $HOME/downloads/fnord http://fnord.example.com/script.exe
ln -s $HOME/downloads/fnord $HOME/bin/

This assumes $HOME/bin is in your PATH.

There are tools like stow which do this -- and much more -- behind the scenes for you.

This may vary slightly depending on the Unix flavour. I'm assuming Linux here (although this could apply to OSX). According to the Filesystem Hierarchy Standard (FHS) (link obtained from the Linux Standard Base working group):

The /usr/local hierarchy is for use by the system administrator when installing software locally. It needs to be safe from being overwritten when the system software is updated. It may be used for programs and data that are shareable amongst a group of hosts, but not found in /usr.

Locally installed software must be placed within /usr/local rather than /usr unless it is being installed to replace or upgrade software in /usr.

/usr/local/bin is often on the path by default.

Note that you should only put the executable or a link to it in /usr/local/bin, the rest may have to go in /usr/local/lib or /usr/local/share.

The /opt tree might also be sensible:

/opt is reserved for the installation of add-on application software packages.

A package to be installed in /opt must locate its static files in a separate /opt/<package> or /opt/<provider> directory tree, where <package> is a name that describes the software package and <provider> is the provider's LANANA registered name.

[...]

The directories /opt/bin, /opt/doc, /opt/include, /opt/info, /opt/lib, and /opt/man are reserved for local system administrator use. Packages may provide "front-end" files intended to be placed in (by linking or copying) these reserved directories by the local system administrator, but must function normally in the absence of these reserved directories.

(You could make your own link from /opt/your-package/bin/executable into /opt/bin, and put /opt/bin on the PATH if it's not already there.)