Open sublime file from terminal

After doing a lot of stuff in the command line, it becomes boring to go to GUI. For example, let’s say I start a project, and I do something like this:

cd Desktop
mkdir project && cd project
touch readme.md
touch hello_world.py
git init

With just a few keystrokes I created my project folder and files and initialised a git repo. Now, to use sublime text I have to right click and open with the editor or drag the folder/file to the editor. In computer world, this is called context switching which in rough sense means going from one application to another. Context switching both in computer and in the real world is costly in terms of time.

Coming to the point, we can use some tweaks to save this time and enable opening the files from the terminal itself.

Checking if everything is working fine before starting

Running the below command should open the Sublime Text editor:

open -a /Applications/Sublime\ Text.app

Similarly, in order to open any file we can also type something like:

open -a /Applications/Sublime\ Text.app hello_world.py

We want to make life easy and save time but the problem in the above command is that it is too long to type which doesn’t sound like saving time.

The solution to this problem is .bash_profile.

A little background on .bash_profile

.bash_profile is one of the hidden files in our Mac. What it does is it loads the configuration and preferences of the command line interface when we open the terminal.

To view hidden files in any directory, type:
ls -a
To view .bash_profile, type:
cd ~
ls -a

Learn more about some of the most important bash commands in my article - command line cheatsheet

So, in order to make an alias or short name of the above open sublime command, we can add it to the .bash_profile.

How to edit the .bash_profile and execute sublime shortcut

Step I: Fire up the terminal and type:

cd ~

This will take you to the home directory, where .bash_profile resides.

Step II: Type:

vim .bash_profile

This will open the .bash_profile in vim editor in terminal.

Step III: Add below line to the end of your .bash_profile

alias sublime="open -a /Applications/Sublime\ Text.app"

This will create a shortcut command sublime to open any file in sublime text editor.

Step IV: Save changes by pressing Esc button and then typing:

:wq

This command will save the changes and exit the text editor mode.

Step V: Refresh or activate the new changes by typing:

source .bash_profile

Step VI: Now, in order to open any file, go to that directory and type:

sublime script.py

Voila! Enjoy your hack.