4

I'm pretty much completely new to Ubuntu, so bear with me.

I have made a few scrips without the .sh extension and granted them permission with chmod 755, and the scripts run just fine as long as I'm in the directory they are located in, either with ./myscript or sh myscript. Since I want to be able to run these scripts from anywhere I added them to the PATH with export PATH=$PATH:/path/to/directory/. However if I try to run a script with ./myscript the terminal outputs: bash: ./myscript: No such file or directory.

How do I run these scripts outside the directory they're in?

Also worth noting is if I try to run them with sh /path/to/script/ the terminal outputs: sh: 0: Can't open /path/to/script/.

SweGoat
  • 43

1 Answers1

7

Executables, that includes your scripts if they are set as "executable" (File - Properties - Permissions tab), can be executed from any directory just by typing their name, provided they reside in a folder included in the PATH environmental variable.

THE PROBLEMS

There are two reasons why it may not work for you:

1. You are specifying a path

As soon as you indicate a path, e.g. ./, you are telling the system to look for a file in a specific location. ./ means "look in the current directory for the file".

As soon as you call sh or bash, you are calling a different executable. What comes after that, is an argument to that command, in this case the reference to the script you want to run. If you do not provide a path, the script will be looked for in the current directory only.

2. You are not persistently changing the PATH

export PATH=$PATH:/path/to/directory/ will export the new PATH in the environment of your current shell and subshells only. You are not updating your path for any other terminals you open.

THE SOLUTION

1. Persistently set up your path

To persistently change an environment variable

˃ For your user only

Include the command in .profile. This file is a hidden file in your home directory.

Yet better!: Ubuntu is automatically set up to include a folder ~/bin and/or .local/bin in your path if either of these folders exist. So, rather than setting up a custom path, just create one of these folders and put your scripts there! You need to close and reopen the terminal for the new path to take effect.

˃ System wide

Change PATH defined in /etc/environment. You need administrator privileges to edit that file.

Yet better!: Ubuntu automatically includes the /usr/local/bin directory in your path. So, rather than setting up a custom path, just put your scripts there! You need root privileges for that.

2. Just type the file name of the script to execute it.

Do add nothing before the file name. Type the file name exactly as is (case matters). In that context, I find it much easier to remove the .sh extension.

vanadium
  • 97,564