How to write a shell script that you can use anywhere on your computer

This post is to answer a question that someone asked about automating a task with Bash. It’s just how I would do it, and I’m not an expert shell scripter, so if there is a better way, please comment below. :slight_smile:

I put all my projects in a directory called ~/code. If my script were called my_command, I would store it in a file at ~/code/my_command/my_command (no file extension).

The my_command file would contain these contents:


# write your script commands here

After the commands are entered, you can make the script executable by typing this in the same directory as the my_command file:

$ chmod u+x ./my_command

I made a directory on my computer called ~/bin which stores executable files. To link my project (which is in ~/code/some_project_name) to the ~/bin directory, I create a symlink:

$ ln -s ~/code/my_command/my_command ~/bin/my_command

In my terminal’s config file where I set my PATH variable, I add ~/bin to the PATH.


After that is done, you should be able to type this anywhere in the terminal to run your script’s commands:

$ my_command

Yeah… you could do that. And you can also create aliases for things as well.

Since I’m in macOS at the moment, I might add:

alias wifi-scan='/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s'
alias wifi-info='/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I'
alias khosts='nano ~/.ssh/known_hosts'

… to my ~/.bash_profile. Exit the terminal and start it up again (or source the file) and then you have these available to you.

$ wifi-info

     agrCtlRSSI: -23
     agrExtRSSI: 0
    agrCtlNoise: -95
    agrExtNoise: 0
          state: running
        op mode: station 
     lastTxRate: 867
        maxRate: 867
lastAssocStatus: 0
    802.11 auth: open
      link auth: wpa2-psk
          BSSID: 8c:3b:ad:b3:d8:48
           SSID: Nacho-Wi-Fi
            MCS: 9
        channel: 48,80

So that’s a lot easier and more intuitive than the equivalent command or creating a symlink to the airport executable and then forgetting the syntax at the moment of truth.

1 Like