command not found using sudo in script Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of command not found using sudo in script without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am trying to execute sudo command inside a bash script.

#!/bin/bash

sudo node app.js

and it throws me :

sudo: node: command not found

If I try to execute only node app.js (without sudo ),it runs ok.

If I try to just run sudo -h , it prints the sudo help.

But , when I am trying the sudo node app.js it throws me the error.

Answer

Sounds like node is on a non-standard path, or at least not on root’s path. There are a couple of ways around this.

  1. Use the full path to node

    • Find the full path using which node

    • If say it’s in /home/user/bin/node then call sudo /home/user/bin/node app.js

    • Or as @UlrichSchwarz suggested you can combine the two with command substitution: sudo $(which node) app.js

    • Remember the user you sudo to needs read/execute permissions on the location, not as much of an issue when you sudo to root


  1. Call sudo with the -E option to preserve environment variables

We are here to answer your question about command not found using sudo in script - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji