At the start of an administrative script, search only known directories.
Use /usr/local/bin, /usr/bin, and /bin in that order.
Which setting is appropriate?
Setting PATH to known trusted directories reduces differences caused by a user's environment and the current working directory.
Detailed explanation
PATH=/usr/local/bin:/usr/bin:/bin; export PATHCorrect. It fixes the trusted directories and exports the chosen order to child commands.
PATH=$PATH:/usr/local/binIncorrect. It keeps an untrusted user-supplied PATH.
PATH=.:$PATHIncorrect. Putting . first makes execution depend on the current directory.
unset PATHIncorrect. Removing PATH makes command lookup depend on defaults or absolute paths.
Try it yourself
An example you can run in a temporary verification environment.
sh -c 'PATH=/usr/local/bin:/usr/bin:/bin; export PATH; printf "%s\n" "$PATH"'Expected result
/usr/local/bin:/usr/bin:/binKey points
- Fix PATH to known directories
- Make the order explicit
- Do not include the current directory
Notes
- Environment: POSIX sh / 短命プロセス
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Shell function
A reusable group of commands that runs in the caller's shell context.
Positional parameter
A numbered argument or special value supplied to a script or function.
Control flow
Conditions, loops, and exit statuses determine which shell commands run.