Use cases:
You can use the program name to change the program behavior.
For example you could create some symlinks to the actual binary.
One famous example where this technique is used is the busybox project which installs only one single binary and many symlinks to it. (ls, cp, mv, etc). They are doing it to save storage space because their targets are small embedded devices.
This is also used in setarch
from util-linux:
$ ls -l /usr/bin/ | grep setarch
lrwxrwxrwx 1 root root 7 2015-11-05 02:15 i386 -> setarch
lrwxrwxrwx 1 root root 7 2015-11-05 02:15 linux32 -> setarch
lrwxrwxrwx 1 root root 7 2015-11-05 02:15 linux64 -> setarch
-rwxr-xr-x 1 root root 14680 2015-10-22 16:54 setarch
lrwxrwxrwx 1 root root 7 2015-11-05 02:15 x86_64 -> setarch
Here they are using this technique basically to avoid many duplicate source files or just to keep the sources more readable.
Another use case would be a program which needs to load some modules or data at runtime. Having the program path makes you able to load them from a location relative to the program location.
Moreover programs usually print error messages containing their program name.
Why:
- Because it's POSIX convention (
man 3p execve
):
argv is an array of argument strings passed to the new program. By convention, the first of these strings should contain the filename associated with the file being executed.
- It's C standard (at least C99 and C11):
If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment.
Note the C Standard says "program name" not "filename".
sh
is symlink todash
. They behave different, when called assh
or asdash
– Motte001 yesterdaybusybox
(common on rescue-discs and such), then pretty much everything (cp, mv, rm, ls, ...) is a symbolic link to busybox. – Baard Kopperud yesterdaygcc
,bash
,gunzip
, most of the rest of the OS...), as Linux is just the kernel. – wizzwizz4 yesterday