1

This question already has an answer here:

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.

marked as duplicate by Sergiy Kolodyazhnyy, glenn jackman, muru command-line Feb 5 '16 at 5:19

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • shebang shebang shebang ;) – incBrain Feb 5 '16 at 1:06
3

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
    
  • 1
    Besides of using chmod and including the script in a location in your path, you should also make sure that your script starts with a shebang, as told in the comments to the OP. – Marcelo Ventura Feb 5 '16 at 1:59
  • 1
    Also , personal bin folder must be included into the PATH variable, which can be done by uncommenting appropriate line in ~/.profile – Sergiy Kolodyazhnyy Feb 5 '16 at 2:27
  • OK I have added in the suggestions, feel free to trim these as you wish :) – andrew.46 Feb 5 '16 at 4:11
3

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.