Bin and sbin in linux

What are the meanings of /usr/sbin, /usr/local/sbin and /usr/local/bin?

So the question is: Why there are so many directories and what are the meanings of /usr/sbin , /usr/local/sbin and /usr/local/bin ?

Many programs are distributed through archives and we have to build them from source code. Usually they have makefile so it’s quite easy. This process involves creating files in usr/local/lib, usr/local/bin. usr/local/whatever without creating specific folders for a given program.

I think it’s not right because if we need to remove the program we have to manually delete every of its files if the program’s creator didn’t take care of it.

Sergey, please use the Markdown syntax for writing posts on Super User. Having HTML in them makes them really hard to read and edit in plain text.

I hate directory filesystems. why doesn’t somebody invent a filesystem where files are just tagged instead ? On top of it, directories don’t make any sense because inodes allow files to be fragmented. A directory should be an allocated part of the hard drive memory space, not some path, mostly like a partition.

Btw. the normal way to deal with the «uninstallability» issues of locally built programs is to actually build local packages for them. This process is, however, very dependent on the Linux distribution. In case applications support that mode of deployment, modern supplements to the established packaging systems like Flatpack or Docker come to mind.

5 Answers 5

1. Directory structure

/bin/ Essential command binaries that need to be available in single user mode; for all users, e.g., cat, ls, cp /sbin/ Essential system binaries, e.g., init, ip, mount. /usr/bin/ Non-essential command binaries (not needed in single user mode); for all users /usr/sbin/ Non-essential system binaries, e.g. daemons for various network-services. /usr/local/ Tertiary hierarchy for local data, specific to this host. Typically has further subdirectories, e.g., bin/, lib/, share/

2. Installation

I use a package manager wherever possible (e.g. yum or apt-get). This is possible for a very large number of applications, in a few cases you may have to add a repository. My second choice would be lower level packages such as RPMs and compiling from source would be my last resort (but some people prefer this)

Some package managers can install from RPMs (e.g. yum install oddity.rpm )

If you are compiling from source, its probably not a huge step to create your own package so that the system installer knows what you’ve done.

Then your problem reduces to e.g. yum remove packagename

The alternative is to keep good documentation about all sysadmin activities undertaken (I keep a journal in a text file anyway)

I still don’t get the difference between usr/sbin, usr/local/bin and usr/local/sbin. usr/local is said to be specific to this host, aren’t usr/sbin, usr/bin also specific to the host? the second question was about those programs which are not in repos — make uninstall doesn’t work always — so I asked how to delete those ones?

Читайте также:  Show process capability linux

@Sergey This is historic. /usr/(s)bin tended to be mounted from a network filesystem. That is why everything that is needed to boot the machine had to be in /(s)bin . For the most part /usr/local is now used for programs that you install outside of the package manager (which you shouldn’t do).

for manually installed programs that you no longer need just do a regular delete ( rm ). /usr/local is for machine specific data as for network booting systems /usr in often a network share. @Let_Me_Be installing programs from outside the package manager is perfectly fine and can often been required.

@Sergey: If you have two computers, installed from the same medium and later manually add some software to just one of them, traditionally this would go in /usr/local as it is local to that machine and not part of the «standard» set of programs provided by the vendor. As others have said, this historical practice isn’t nowadays much followed by package builders — I suppose software in the standard repositories are effectively treated more as vendor-supplied optional software rather than as user-installed local customisation.

Stuff in all the */sbin directories tend to be only useful for system administrators. You can keep them out of your PATH if you’re a normal user.

The different directories don’t make much sense if you have a single unix machine on a single disk, but make more sense if you have a big system and different partitions. Remember that a lot of these habits were made in the 80’s and 90’s when systems were a bit different.

/sbin tends to be very small. These are utilities that you need when you’re really hosed. You’d put this on a minimal root partition with /root and /lib. Things in /sbin used to be all statically linked, since if your /usr partition is hosed, any dynamically linked apps are useless. fsck is here and statically linked. If you have a dependency on /usr, obviously you can’t fsck /usr/. Of course, if root partition is hosed, you’re very screwed. This is why this is such a small partition — lower the odds of a bad disk block by using very few blocks here.

/usr/sbin binaries are general sysadmin tools where you can at least get to single user mode and mount all your volumes. They are allowed to be dynamically linked.

The separate partitions for /sbin (well, /sbin on / partition) and /usr also make more sense when you remember that backup was very expensive in both time and for tape. If they were on separate partitions, you could schedule them differently.

/usr/local can be a network filesystem. So locally written sysadmin tools that can be shared across many machines sometimes go into /usr/local/sbin. Obviously no network fixing utils can go there.

Again, a lot of things made more sense on big machines in a networked environment on managed machines with multiple volumes, less so with one Linux machine on a single root partition.

Источник

Differences between /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, /usr/local/sbin

Your own scripts should go into ~/.local/bin , according to systemd and XDG. See the answers here and here for more.

Читайте также:  Linux cat etc release

2 Answers 2

  • /bin : For binaries usable before the /usr partition is mounted. This is used for trivial binaries used in the very early boot stage or ones that you need to have available in booting single-user mode. Think of binaries like cat , ls , etc.
  • /sbin : Same, but for binaries with superuser (root) privileges required.
  • /usr/bin : Same as first, but for general system-wide binaries.
  • /usr/sbin : Same as above, but for binaries with superuser (root) privileges required.

if I’m writing my own scripts, where should I add these?

None of the above. You should use /usr/local/bin or /usr/local/sbin for system-wide available scripts. The local path means it’s not managed by the system packages (this is an error for Debian/Ubuntu packages).

For user-scoped scripts, use ~/bin (a personal bin folder in your home directory).

The FHS says for /usr/local :

Tertiary hierarchy for local data, specific to this host. Typically has further subdirectories, e.g., bin/ , lib/ , share/ .

Does placing scripts in /bin cause any problems? I have moved my scripts according to your answer but I am still curious

@RumeshSudhaharan you should not do that, because it’s managed by the package management. If any other package also wants to use that path, it will overwrite your file. Files in packages can never overlap (at least for official repositories), so you are more safe when installing in the local path. Also, it’s just for your own convenience and safety. In a local path you can’t mess up the system in such a bad way and you can’t accidentally replace a system binary.

I have put some files in /usr/local/bin and I can execute them, however I cannot edit them, ls -la shows nothing

FWIW, sbin has nothing to do with scripts. It stores binaries — even the links provided note that.

I had a similar question myself a year+ ago: Best directory to place my bash scripts?

System directories for binaries

man hier (hierarchy) lists all the directories. To get the ones just for binaries use:

$ man hier | grep -E 'bin$|sbin$|^.(/bin)|^.(/sbin)' -A2 /bin This directory contains executable programs which are needed in single user mode and to bring the system up or repair it. -- /sbin Like /bin, this directory holds commands needed to boot the system, but which are usually not executed by normal users. -- /usr/X11R6/bin Binaries which belong to the X-Window system; often, there is a symbolic link from the more traditional /usr/bin/X11 to here. -- /usr/bin This is the primary directory for executable programs. Most programs exe‐ cuted by normal users which are not needed for booting or for repairing the -- /usr/local/bin Binaries for programs local to the site. -- /usr/local/sbin Locally installed programs for system administration. -- /usr/sbin This directory contains program binaries for system administration which are not essential for the boot process, for mounting /usr, or for system 

Where to put your own scripts?

For all users to access your scripts you can put them in /usr/local/bin . Keep in mind you need sudo access to add / change files here. See: Is there a standard place for placing custom Linux scripts?

Читайте также:  Ubuntu i686 linux gnu

For your own user ID scripts put them in /home/YOUR_NAME/bin . Keep in mind you have to create this directory first and relaunch the terminal to get the path automatically setup by ~/.profile . See: How to add /home/username/bin to $PATH?

What I know I don’t know

I’m contemplating taking some of my more complex bash scripts in Ask Ubuntu and setting them up with install scripts on github . Here are few examples:

I think the scripts should be installed in /usr/bin which is in the $PATH, but I’m not sure on the appropriate place yet.

Источник

Еще одно мнение о разнице между bin, sbin, usr/bin, usr/sbin

Недавно я обнаружил вот такую статью: Разница между bin, sbin, usr/bin, usr/sbin. Хотелось бы поделиться своим взглядом на стандарт.

/bin

Содержит команды, которые могут использоваться как системным администратором, так и пользователями, но которые необходимы, когда не смонтированы никакие другие файловые системы (например, в однопользовательском режиме). Он также может содержать команды, которые косвенно используются скриптами.

Там ожидается присутствие таких команд:

cat, chgrp, chmod, chown, cp, date, dd, df, dmesg, echo, false, hostname, kill, ln, login, ls, mkdir, mknod, more, mount, mv, ps, pwd, rm, rmdir, sed, sh, stty, su, sync, true, umount, uname.

Можно сделать симлинки на /usr, но хотя во времена systemd /usr на отдельном устройстве не встречается, его еще можно встретить на встраиваемой системе, светофоре, кофемолке и PDP-11 обслуживающем важный прибор в одной из лабораторий Академии Наук.

/sbin

Утилиты, используемые для системного администрирования (и другие команды только для root), /sbin содержит двоичные файлы, необходимые для загрузки, восстановления, восстановления и/или восстановления системы в дополнение к двоичным файлам в /bin. Программы, выполняемые после того, как /usr монтируется (когда проблем нет), обычно помещаются в /usr/sbin. Локально установленные программы системного администрирования должны быть помещены в /usr/local/sbin.

fastboot, fasthalt, fdisk, fsck, getty, halt, ifconfig, init, mkfs, mkswap, reboot, route, swapon, swapoff, update.

Один из способов защиты системы от шаловливых рук юзеров — это запрет запуска этих утилит кому-попало, установкой атрибута x.
К тому же, замена /bin и /sbin на копии из архива (одинакового для всех однотипных систем) является быстрым способом починки систем без пакетного менеджера.

/usr/bin

Тут всё просто. Однотипные команды, одинаковые для всех серверов/кофемолок компании. И сам /usr может разворачиваться одинаковым для разных ОС (для /bin и /sbin такое как правило не работает), это архитектурно независимые программы. Может содержать линки на интерпретаторы perl или python, которые лежат в /opt или еще где-то в сети.

/usr/sbin

Тоже самое, что /usr/bin, но для использования только админами.

/usr/local/bin и /usr/local/sbin

Одна из важнейших локаций. В отличие от остального, /usr не может быть одинаковой для всей организации. Тут находятся ОС-зависимые, hardware-зависимые и просто программы, которые не на всех устройствах нужны. При синхронизации /usr на машинах, /usr/local требуется исключать.

/home/$USER/bin

Тут случай аналогичный с /usr/local, только лежат программы специфичные для конкретного пользователя. Можно переносить (или синхронизировать) на другую машину при переезде пользователя. То, что нельзя переносить складывается в /home/$USER/.local/bin. Можно использовать local без точки. /home/$USER/sbin по понятным соображениям отсутствует.

Буду рад исправлениям и дополнениям.

Источник

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