1

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.

giga
  • 183

2 Answers2

4

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
muru
  • 197,895
  • 55
  • 485
  • 740
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
    
andrew.46
  • 38,003
  • 27
  • 156
  • 232
  • 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 05 '16 at 01: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 05 '16 at 02:27
  • OK I have added in the suggestions, feel free to trim these as you wish :) – andrew.46 Feb 05 '16 at 04:11