Skip to content

Instantly share code, notes, and snippets.

@joshwyatt
Last active January 22, 2024 20:41
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save joshwyatt/a6e20d28818b5183258b to your computer and use it in GitHub Desktop.
Save joshwyatt/a6e20d28818b5183258b to your computer and use it in GitHub Desktop.
How to make scripts you can access globally from the terminal

How to make a globally available executable script in the scripting language of your choice

  • Locate the path to the interpreter for the language you are writing in with the which command.

      which node
      which python
      which bash
      which ruby
    
  • Add that path as an interpreter directive (using #!) on the first line of your script. For example if you want to write a node script and which node returned /usr/local/bin/node, the first line of your script should be:

      #! /usr/local/bin/node
    
  • Write your script to do what you want.

  • Give your script execute permissions for your user with chmod u+x <path_to_your_script>. For example if your script is called myScript.js and is located in your current directory:

      chmod u+x myScript.js
    
  • Move your script to one of the directories in the path. You can discover which directories are in your path by typing echo $PATH into the command line, which will print a colon seperated list of each of the directories in your path. A common directory in the path for scripts you've written is /usr/local/bin/. You will probably need to use sudo to be able to move your file into that directory. If the script you've written has a file extension in its name, and/or some case, like camel case you'd rather modify, be sure to remove the extension and change the name of the script as you wish. Continuing with the example script called myScript.js:

      sudo mv myScript.js /usr/local/bin/my_script
    
  • Alternatively, you can create a link to your script inside the path, without actually moving your script. ln <source_file_path> <destination_path> will accomplish this. Continuing with our same example:

      sudo ln mySript.js /usr/local/bin/my_script
    
  • Use your script you're done. Tab completion will now work when you want to run your script, and which my_script will disclose its location. If you need to make edits just open the file in its new location and go to town.

@ynbh
Copy link

ynbh commented Aug 10, 2022

Hey, first off, thanks for this!

I just had a question:

  • What if the script utilises packages from NPM?

I followed these steps for a quick CLI tool I made with zx and unified, and was wondering on how to make it work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment