Today, I'm going to be sharing a little trick I use to teleport around my terminal with ease.
Do you change to your project directory like this?
> ~ $ cd Documents > ~/Documents $ cd projects > ~/Documents/projects $ cd my-project > ~/Documents/projects/my-project $ ls src/ package.json yarn.lock etc...
Then this article is for you!
If you have directories that you commonly go to, it can be incredibly useful to create aliases using pushd.
If you don't know anything about your bashrc, pushd, or setting up aliases, check out my Bash Script Tool Kit blog.
We can try adding something like this to our bashrc:
alias projects="pushd ~/Documents/projects" alias experiments="pushd ~/Documents/experiments"
Now, anytime we type
experiments into our terminal, we can instantly "teleport" to these directories!
But it doesn't stop there, folks! You're probably asking yourself right now, "Jimmy, why use pushd when cd would do the same thing?"
That's a very good question! Pushd has a special feature. After we pushd into a directory we can use popd to pop back to the directory we were previously in. Say we are in our experiments folder and we type in
projects into are terminal. Now, if we want to go back to our experiments directory, all we have to do is type
popd and we're back were we were!
&& is a very useful and powerful tool when it comes to writing bash alias. It lets us chain commands after one another in one line! So lets use this
&& operator to chain some extra commands and improve our scripts.
alias projects="pushd ~/Documents/projects && clear && ls" alias experiments="pushd ~/Documents/experiments && clear && ls"
You can see here that we've chained
ls to our commands. So now when we use the projects alias it will take us to our projects directory, clear our screen, and list out all the files and directories. Pretty sweet, huh?
Another alias I use quite a lot is:
alias x="clear && ls"
How many times do you do this:
$ cd .. $ ls
Why not set up a couple of aliases that do the hard work for you?
alias ..="cd .. && clear && ls" alias ...="cd ../.. && clear && ls" alias ....="cd ../../.. && clear && ls" alias .....="cd ../../../.. && clear && ls"
.. will take you up a directory, clear the screen and list out all your files in that directory for you. Pretty neat, huh?
Combine the use of chaining with
pushd we can create some incredibly useful alias that help us not only teleport around our filesystem, but keep it clean and organized as well.
What are some of your favorite bash scripts or aliases? I'd love to hear about them in the comments!