Set PATH Explicitly in a Privileged Shell Script
Set PATH=/usr/bin:/bin at the top of a privileged script so a hostile directory in the caller's PATH cannot replace ls, cp or tar with its own program.
A script run by cron or through sudo calls tools by name, and whoever controls the PATH it inherits controls which programs run.
mkdir evil && printf '#!/bin/sh\necho "evil ls was here"\n' > evil/ls && chmod +x evil/ls
cat > tool.sh <<'EOF'
ls -d /tmp
EOF
PATH="$PWD/evil:$PATH" bash tool.sh
cat > safe.sh <<'EOF'
PATH=/usr/bin:/bin
ls -d /tmp
EOF
PATH="$PWD/evil:$PATH" bash safe.shevil ls was here
/tmpA command with no slash is looked up in the directories of PATH from left to right, and the first match runs. The first script runs the planted ls, which prints its own message, because the caller put its directory first. Assigning PATH in the script replaces the caller's value, so the second script runs the system binary and lists the directory. The lookup order is defined in the shell command search rules.
Setting PATH does not help against a hostile /usr/bin, nor against a variable such as LD_PRELOAD, which sudo already strips by default. Use absolute paths for tools outside the fixed list. Scripts that depend on tools in /usr/local/bin or in a version manager's directory need those directories added deliberately.