This is context dependent and both options have their advantages and disadvantages. On balance I would avoid using absolute paths unless you have a very specific reason to do so.
Calling using PATH environment variable
Calling commands without specifying their absolute path (IE using their existence in a PATH
directory) can make a script more portable. This is perhaps less likely to be an issue for programs in /bin
but definitely true for any commands you expect to be in /usr/bin
. Different systems can put these in all sorts of places such as /opt
or /snap
.
Worse, users can configure their path for many different reasons. This may include such things as having multiple java runtimes or python versions installed. So any call to java
should almost never be /usr/bin/java
because they system administrator may have installed a version which is incompatible with your script. Allowing the user to choose which java version to use is vital.
Another example of this is that some distributions don't necessarily follow the conventions that you expect. In fact Archlinux has bundled /bin
/sbin
/usr/bin
/usr/sbin
all into one directory with symlinks to the others (see here). That should be backwards compatible but it demonstrates that some standards are not as ubiquitous as you may believe.
Note that tools such as sudo have specific protections for the PATH environment variable built in so it is generally safe to assume that scripts which need to be run with sudo will be secure even if you don't specify the absolute path.
Calling using absolute path
Usually you only use the absolute path when you have a very specific reason to do so.
The primary advantage of using absolute paths is that you have more control over precisely which commands are being run. This can be where you have specific alternative tools installed which are intended to override the user specified path.
You have pointed out the question of security. There are ways that this can be useful, but as noted sudo
executed commands are rarely an issue.
You mention cron scripts. Famously cron has a problem with the PATH environment variable in that it is not often set as you expect (see here). I have in the past written scripts with absolute paths for use with cron. This was more because I didn't trust the sys-admin installing it. My preference would be always to run cron jobs with a well setup PATH rather than absolute paths in the script.