How do you execute a script called myscript
?
sh myscript # Or sh /path/to/myscript
bash myscript # Or bash /path/to/myscript
perl myscript # Or perl /path/to/myscript
python myscript # Or python /path/to/myscript
etc.
This is easy but you do need to know which interpreter to use to run the script, and as you have noticed trying to use the wrong one will generate errors (for example using sh
instead of bash
).
Better, is to let the script declare the correct interpreter itself. This is defined using the #!
on the first line. For example this line would declare bash
(specifically /bin/bash
) as the interpreter:
#!/bin/bash
To use this feature you need to make the script executable,
chmod a+x myscript
and then provided it is in one of the list of colon-separated directories specified in $PATH
you can run it exactly like any other program - with just its name
myscript
However, notice that the current directory (notated as .
) is not in $PATH
so if you're working on a script in the current directory, you will need to provide a path to the script so that it can be found. Here the .
represents current directory and it's a path relative to your current working directory (i.e. the same place):
./myscript # Or /full/path/to/myscript
There are good reasons why .
is not usually in the $PATH
, but if you must add it then put it at the end of the $PATH
rather than the beginning. (See History of UNIX not including current directory in $PATH and Why is . not in the path by default?.)
Notice that the script name or extension does not matter (unless you end up using a command name such as test
that's already present in the system directories listed in $PATH
). I've used myscript
as the example here. You could use myscript.sh
if you wanted, or even confusion.png
, but you don't use ls.exe
so I don't see a need to have myscript.sh
. Be aware, though, that some GUIs may use file extensions to guess what's in the file and using extensions in a nonstandard way (such as png
for a script) may confuse them. The proper way for a GUI to identify file contents would be to use an equivalent to the file
command, but not all of them do that:
file myscript
Finally, when I've finished working on a script I'm going to reuse I tend to put it into a directory that is included in my $PATH
. It then becomes a tool as easy to access as ls
or cp
. In my case I use $HOME/bin
but you can choose any directory you like as long as it's listed in $PATH
.
ls -l /bin/sh
? I assume that has a symlink todash
(another shell) – Edgar Magallon Jan 26 '23 at 06:05PATH
, you need to give the path explicitly, e.g../raw_io
. – ilkkachu Jan 26 '23 at 06:06./raw_io 10
and you'll have ample time to copy its output. – Artem S. Tashkinov Jan 26 '23 at 07:57