Cristian
Cristian

Reputation: 1670

How to execute a bash script without calling its path?

I have the file script.sh in my-directory folder.
How to run this script with the command `script' from the terminal with no regards to the location I am in the terminal?

Upvotes: 0

Views: 5094

Answers (2)

Inian
Inian

Reputation: 85683

You can do so by exporting the path where your script in the PATH environment variable, so that you don't ever have to worry about what your actual script's location is, i.e. if your script is present under say /path/to/dir, do

export PATH=$PATH:/path/to/dir

so that your script's path gets appended to an already existing set if paths under PATH, also remember if you run the above from the command-line, it is not permanent and gets lost soon after the session is terminated. To make it permanent add the same line in .bashrc (or) .bash_profile, depending upon your environment.

Or creating a symbolic link from /usr/bin that is what you intent to do you can do something like ln -s /full/path/to/myscript.sh /usr/bin/myscript and then run as just myscript directly from command line. You can also confirm if is properly added by checking the script's location by which command,

 $ which myscript
/usr/bin/myscript

Upvotes: 2

shiv
shiv

Reputation: 1952

Say your directory is /home/Cristian/my-directory then you can make that part of PATH environment variable like export PATH=$PATH:/home/Cristian/my-directory and then you will be able to call it by typing script.sh and not script. If you want it to be called as script then you should name it script and rename the extension.

The export command will make the directory in question part of PATH temporarily. To make it permanent you may want it to part of .bashrc or other shell rc file if you are in other shells.

Upvotes: 1

Related Questions