Why use install rather than cp and mkdir?
It depends on what you're doing.
The install
command is normally used in installation scripts that come with packages and source code for installing a binary to your system. It can also be used to install any other file or directory. In addition to the -d
and -c
options you have -m
for specifying the new permissions of the file to be installed, so you don't have to do a cp
and a chmod
to get the same result. For instance:
install -m644 "$srcdir/$pkgname-$pkgver-linux64" "$pkgdir/opt/$pkgname"
You also have options -g
and -o
for setting the target group and owner, respectively. This avoids separate calls to chown
. In general, using install
shortens your script and makes it more concise by doing file creation, copying, mode setting and related stuff in one command instead of many.
For reference, see man install
. For usage, just take a look at any installation script shipped with some package source code.
"install" generally combines the following actions:
- Copying of the specified file to the target place, which is being done with respect to processes which use an old copy. Unlike "cp", "install" either unlinks file before the creation of a new one, or (in BSD systems, with -S switch) creates a new one and renames to the target name atomically, which avoids race condition between installing and reopening. If not to use this, copying could fail (with ETXTBSY) for a running binary file, or cause a crash if a library file or a data one is replaced.
- Set proper permissions of the new file without need for separate commands.
- Make intermediate directories, if requested.
- Avoid modifying of a target file if it's identical to the new version (-C switch).
So, it follows Unix approach that a tool shall be made for a single but complete action of installing a file made by a some building tool to its working location.
The complete concept as I've described is implemented in BSD systems (in so-called "xinstall" version); I treat here "safe copy" mode (new version with atomic renaming) as vital for this. Linux systems (from coreutils) miss this important part and are prone to races between deleting and reopening by a bystander process; but this could have been covered by package managers.
Apart from the previous descriptions here about the usage, there is a low level difference between cp
and install
, at least on Linux. If copying over an existing file, cp
overwrites the existing inode of the file, while install
always creates a new inode for the same file name.
This makes a difference when installing a new version of a running binary. Using cp
causes an EBUSY error, while install
will succeed. The running binary will still use the old version, but the new version is used if the program is restarted.