Here is my code:
#!/usr/bin/node
console.log('HELLO')
This file has been named test
. No extension. If I try running it in my terminal like so
$ test
There is no output. However, if I run
/usr/bin/node test
I get the desired output:
HELLO
Why isn't my script giving the same results?
When you type a command, and it's not an absolute or relative path (like ../test, or /bin/test, or ~/test), then the shell has to search for the executable. It does this by looking in the directories specified in $PATH. You can print it:
> echo $PATH
/usr/local/bin /usr/bin /bin /usr/sbin /sbin
Notice that the current directory .
is not in PATH. This is deliberate: if PATH contained .
, then it's possible that a command may be accidentally or maliciously overridden by a file in the current directory.
You can ask which command you'd get:
> which test
/bin/test
That's what's being run, and why there's no output.
To run a command that's not in PATH, use an absolute or relative path:
./test
That should fix your problem.