How to run a script from terminal [duplicate]

Hi I would like to run a script from the terminal, is there anyway to do that? For example : if I have a python script I would normally run it with this command :

python script.py

How can I run this script just by typing in the filename of the script in the terminal (even if i'm in another directory) ?

Another answer I found pretty helpful : How to run scripts without typing the full path?

You can just create symlink. Create it in /usr/local/bin. All you need is to run command:

sudo ln -s /full/path/to/your/file /usr/local/bin/name_of_new_command

After that you should make your file executable:

chmod +x /full/path/to/your/file

Now you should be able to run name_of_new_command at any time in your terminal.

Note that this is good solution only for home usage of Linux.


Solution 1:

Put this line in your .bashrc assuming you're using bash as shell:

export PATH=/path/to/your/script/:"$PATH"

You can use vi, nano or gedit to edit this line in the end of the file. Make sure your script is set to executable mode, if it's a bash script:

chmod +x script.sh 

Or if it's a Python script:

chmod +x script.py

On your script indicate their type in the first line. If it's Python:

#!/bin/python 

If it's bash:

#!/bin/bash

Solution 2:

Perhaps the easiest way to do this is to place your script in $HOME/bin and making sure that the permissions are set to executable:

chmod +x  $HOME/bin/script.py

Now you should be able to run the script from any directory....

A couple of other points to be aware of:

  1. Ensure that $HOME/bin is in your $PATH, for Ubuntu this will be set by default in $HOME/.profile but it does not hurt to check.
  2. Ensure that your Python script has the appropriate 'shebang' set:

    #!/usr/bin/env python