How to make a shell script global?

In mac operating system

  • Open bash ~/.bashrc file.
  • add path of your script in your bashrc file , using export PATH="$PATH:/Users/sher.mohammad/Office/practice/practiceShell"
  • Open your ~./bash_profile file and add [[ -s ~/.bashrc ]] && source ~/.bashrc
  • open new terminal window Now whenever you will open your terminal your script will be loaded

/usr/local/bin would be the most appropriate location. Mac OS X has it in the PATH by default


Traditionally, such scripts either go in ~/bin (ie: the bin directory in your home directory) or /usr/local/bin/ The former means the script will only work for you, the latter is for scripts you want anybody on the system to be able to run.

If you put it in ~/bin, you may need to add that to your PATH environment variable. /usr/local/bin should already be on the path.


There are two ways to do it -

  1. Put your script in usr/local/bin and make sure it is executable(chmod +x my_script)(This is already set in the path, you can check by doing an echo $PATH)
  2. Create a folder in your home directory called bin. (For your personal scripts)
    • cd ~ (Takes you to your home directory)
    • mkdir bin (create a bin folder)
    • vim .bash_profile (to set path environment variable)
    • export PATH=~/bin:$PATH (Press i then add this line and then do esc and type :wq)
    • Now you can just type the name of your script and run it from anywhere you want.

** NOTE: If you want to run the script with a shortened command rather than typing your entire filename, add the following to your .bash_profile:
alias myscript='my_script.sh'
Then you can run the script by simply typing myscript. (you can sub in whatever alias you'd like)

Tags:

Unix

Macos

Shell