Forgetting That the Current Directory Is Not in the $PATH
Problem
You’ve got your script all written and want to try it out—you even remembered to add the execute permissions to the script, but when you go to run the script you get an error message:
$ my.script bash: my.script: command not found $
Solution
Either add the current directory to the $PATH
variable, which we do not recommend, or
reference the script via the current directory with a leading ./
before the script name, as in:
$ ./my.script
Discussion
It is a common mistake for beginners to forget to add the leading
./
to the script that they want to
execute. We have had a lot of discussion about the $PATH
variable, so we won’t repeat ourselves
here except to remind you of a solution for frequently used
scripts.
A common practice is to keep your useful and often-used scripts in
a directory called bin inside of your home
directory, and to add that bin directory to your
$PATH
variable so that you can
execute those scripts without needing the leading ./
.
The important part about adding your own bin
directory to your $PATH
variable is
to place the change that modifies your $PATH
variable in the right startup script.
You don’t want it in the .bashrc script because
that gets invoked by every subshell, which would mean that your path
would get added to every time you “shell out” of an editor, or run some
other commands. You don’t need repeated copies your
bin directory in the $PATH
variable.
Instead, put it in the appropriate login profile ...
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.