Normally, to run a script on Linux you would have to call it with the name of the application, for example with a Python script myscript.py
you would type something like:
$ python myscript.py
… or, if it was a shell script named myscript.sh
:
$ bash myscript.sh
You can remove the need to explicitly call the application which runs the script if you have set the correct #!
hash-bang entry as the first line of the script and then set the script file to be executable.
By default our script file will not be executable. Check by using ls -l
:
$ ls -l myscript.py
-rw------- 1 n1234 mygroup 47091 Nov 4 12:49 myscript.py
$
Notice the lack of x
entries in the permissions columns. We can add execute with the chmod +x
:
$ chmod +x myscript.sh
$ ls -l myscript.py
-rwx------ 1 n1234 mygroup 47091 Nov 4 12:49 myscript.py
$
Note that the script now shows x
in the owner permission column. The script, as long as it has a valid #!/bin
hash-bang first line should now run by simply calling the file itself, e.g.:
$ ./myscript.py
Most hash-bang paths specify the absolute path and filename of the application which runs the script, e.g:
#!/bin/bash
… or …
#!/usr/bin/python3
In most circumstances this is okay, but on an HPC system where the version of Bash, Python, R or other runtime applications may very well differ it is often easier to use the following convention:
#!/usr/bin/env python3
The /usr/bin/env
command, instead of directly calling python3, will search all of the available $PATH
directories for python3. This means that regardless of which Python 3 module you decide to load, it will always call the current version.
You can use the same trick for Perl, R, Ruby and other script runtimes which you would normally explicitly set via the hash-bang line.