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.
$HOME/bin
move you script there, logout/in and they should work with your path. – Nov 09 '20 at 16:56./
in front of the script. That is only needed when you are in the same directory as the script without the path to the script added. – Terrance Nov 09 '20 at 17:18export PATH
command every time you open a new terminal, you need to make it persistence. See the answer written below. My scripts are added to my~/bin
folder that way I didn't have to make any changes to the PATH at all. Also, when you're making your scripts executable, are you adding the "shebang" line as the first line in your script? The line is either#!/bin/bash
or#!/bin/sh
or whatever you need as the interpreter. – Terrance Nov 09 '20 at 17:27