Interview Prep/Shell Scripting/Troubleshooting: tools, portability, permissions and environment

`kubectl` works for you, but in a script `sudo kubectl apply -f deploy.yaml` fails with `sudo: kubectl: command not found`.

IntermediateTroubleshootingTroubleshooting: tools, portability, permissions and environment
Answer

Likely causes → sudo replaces PATH with secure_path from /etc/sudoers (typically /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin), so binaries in ~/.local/bin, /snap/bin or /opt/*/bin are not found. sudo also resets most environment variables, so KUBECONFIG would be lost too.

Diagnose →

command -v kubectl                 # /home/alice/.local/bin/kubectl
sudo sh -c 'echo $PATH'
sudo grep -r secure_path /etc/sudoers /etc/sudoers.d/

Fix → Usually the real fix is to not use sudo: kubectl talks to an API server and needs no root. If root is genuinely required, use an absolute path and pass only what is needed: sudo /usr/local/bin/tool --config /etc/tool.conf.

Prevent → Install shared tooling into /usr/local/bin, avoid sudo for non-privileged CLIs, and use absolute paths for anything run via sudo.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Troubleshooting: tools, portability, permissions and environment