Become a hero in the Bash Shell
Stijn Dejongh
Hands-on software solution architect | freelancer | husband | father | human
Why do I like my Command Line Interface tools so much?
The reasons are remarkably simple, actually:
Most of these CLI advantages stem from what we call the Unix philosophy:
Do one thing. Do it well.
In essence, this means emphasizing simplicity, brevity, clarity, modularity, and extensibility in code. It makes life easier for both developers and users, ensuring that tools are easy to maintain and adapt.
Now, it's your choice where to go from here. You can take the blue pill, and the story ends here. You click away from this article, do something else, and believe whatever you want to believe.
Or, you can take the red pill, and read on. We stay in console land, and I'll show you how deep the rabbit hole goes.
The joy of CLI aliases
Still here?
Good. I knew you′d make the brave choice.
In the rest of this article, we will talk about the use of Command Line Aliases, and end with a step-by-step guide to set up your own. To give you a head start, I included my own alias files at the end of this page. You can copy and use these, modifying them to your own specific needs and preferences.
A CLI alias, like a nickname, is nothing more than a shorthand for a longer command. Type in the alias into your terminal, and the command it's linked to will be executed. This means you can create abbreviations for your most frequently used operations, alternate versions for the commands you tend to mistype often, or create custom pipelines by combining existing commands and shell scripts into one.
For the sake of brevity, we will not go into shell scripting in this article, but stick to the basics of using aliases to speed up your flow.
Navigational aliases
One of the most underrated alias categories is the "navigational aliases" one. These are just shorthands for jumping around your system quickly.
As an example: my code projects all reside in the same directory on my machine. When I open a new terminal, it is located in my user directory (or home folder). Typing code let's me jump into my programming projects immediately.
alias code="cd /media/stijnd/DATA/development/projects"
Compare this to opening a file explorer window and clicking through various folders to get to this location. You will save dozens of seconds every time. While this might not seem like much, those seconds quickly add up.
Build System aliases
If you are a software developer, you will often need to build/generate your code. Here is an example of my own aliases to common Maven build commands.
# MAVEN ALIASES
alias mci="mvn clean install"
alias mi="mvn install"
alias mrprep="mvn release:prepare"
alias mrperf="mvn release:perform"
alias mrrb="mvn release:rollback"
alias mdep="mvn dependency:tree"
alias mpom="mvn help:effective-pom"
alias mst="mci -Dmaven.test.skip=true"
alias msonar='mci org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.login="API_KEY_GOES_HERE"'
Most of these are just shorthands for commands that I commonly use. The msonar one is different. It is a command to send my code to the SonarCloud static code analysis tool. It's aliased because I always seem to forget the command, and because I do not want to copy my sonar API key every time I do this.
A word of caution here: DO NOT PUT YOUR PASSWORDS IN YOUR ALIAS CONFIGURATION. Just don′t do it.
Version control aliases
Git can be daunting. There are a lot of options, and the tool is incredibly powerful. You can use it for precision surgery, but also to cut off your own leg.
We′d like to avoid hurting ourselves if we can. This is why adding aliases for the more troublesome, or hard-to-remember, commands can be a big help.
Let's look at some examples from the configuration files that are included in the "References && Tools" section of this article.
Squash
squash = "!f(){ git reset --soft HEAD~${1} && git commit --edit -m\"$(git log --format=%B --reverse HEAD..HEAD@{1})\"; };f"
The squash alias allows you to tidy up your commit history by merging multiple commits into a single one. You'll even have the chance to refine the commit message for this new combined commit. This is particularly useful when wrapping up a feature implementation, just before merging your changes into the main branch. No one needs to know about those quirky commit messages like "Please work....", "It will definitely work now", "Fixing the fix", or "WORK, DAMN IT!".
Cleaner log
lg = "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
The default git log output can be quite verbose and not particularly easy on the eyes. With the lg alias, you get a more minimalistic and stylish version of the log messages. Simply type git lg to get a quick and visually pleasing overview of the repository history.
Now, go forth and create your own CLI aliases to supercharge your command line experience.
领英推荐
Guide: How to set up these aliases
Most terminal tools are configured using so called 'dot-files'. The name stemming from the fact that these files generally start with a dot character, which is the *NIX way of creating hidden files. In linux distributions - and windows ports, such as WSL, cygwin, and git bash - the default terminal configuration file is .bashrc.
It is good practice to not stuff this configuration file full of aliases, but rather to put these in a separate file, and load it into your main configuration.
Set up bash aliases
Let's do just that.
Create an empty file, called .bash_aliases in your home directory.
echo '' > ~/.bash_aliases
Then, make your bash configuration load this file if it exists by adding these lines to the end of your .bashrc file:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
If your .bashrc file is not there, you can create one containing only the snippet above.
Set up git aliases
Assuming you are a software developer using Git as a version control system, you might want to set up specific Git aliases.
You can do this by either adding them to the .bash_aliases file or modifying your .gitconfig file. The latter option allows for a more specialized syntax and provides access to Git internal variables.
If you don't have a .gitconfig file, you can create one using Git config commands. This will also populate some initial content in the file. For instance, you can set your Git username:
git config --global user.name "Mona Lisa"
Now, you can add aliases to this file, by adding the heading [aliases]. Each alias should be written on a different line. Pay close attention to the indentation of elements in your file, ensuring they are aligned vertically. On some systems, correct indentation can be critical for your config to load properly.
Choose your weapons
You're well on your way to enhancing your command line experience with aliases. Now, you can take a deeper dive by exploring the example configurations in the "References && Tools" section. Feel free to copy the aliases you find useful into your own configuration files.
One important note: aliases are loaded into a terminal when it's opened or explicitly told to reload. To activate your newly configured aliases, you have two options:
source ~/.bashrc
This command reloads your .bashrc file, making the aliases available for immediate use in your current terminal session.
With your custom aliases and additional configurations from the reference section, you're well-equipped to streamline your command line tasks and boost your productivity.
Happy coding!
References && Tools
I did not go over each of the commands in the configuration files below, so browse through them, and copy anything you like. Or be inspired, and make your own version.
.bashrc include
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
.bash_alias file
# TEXT aliases
alias v="vim"
alias em="emacs"
# GIT ALIASES
alias g=git
alias gcleaner='git fetch -p; git branch -r | awk "{print $1}" | egrep -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk "{print $1}" | xargs git branch -d'
alias glog="git lg"
alias gsquash="git squash"
alias gmetrics="git log --format=format: --name-only | egrep -v '^$' | sort | uniq -c | sort -rh > $1"
# PRODUCTIVITY ALIASES
alias inspire="fortune oblique"
alias fgrab="xclip -sel c < $1"
# KEYBOARD ALIASES
alias workman="setxkbmap us; xmodmap ~/xmodmap/xmodmap.workman && xset r 66"
alias qwerty="setxkbmap us; xset -r 66"
# MAVEN ALIASES
alias mci="mvn clean install"
alias mi="mvn install"
alias mrprep="mvn release:prepare"
alias mrperf="mvn release:perform"
alias mrrb="mvn release:rollback"
alias mdep="mvn dependency:tree"
alias mpom="mvn help:effective-pom"
alias mst="mci -Dmaven.test.skip=true"
alias msonar='mci org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.login="API_KEY_GOES_HERE"'
# DOCKER ALIASES
alias dockerps="docker ps --format 'table {{.ID}}\t{{.Image}}\t{{.Status}}\t{{.Names}}'"
alias dockstruct="docker run -it --rm -v $PWD:/usr/local/structurizr structurizr/cli"
# Bash aliases
alias breload="source ~/.bashrc"
# Directory navigation aliases
alias code="cd /media/stijnd/DATA/development/projects"
.gitconfig file
[user]
email = YOUR_REPO_EMAIL_HERE
name = YOUR_NAME_HERE
[core]
editor = vim
[alias]
# General git usage
squash = "!f(){ git reset --soft HEAD~${1} && git commit --edit -m\"$(git log --format=%B --reverse HEAD..HEAD@{1})\"; };f"
lg = "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
c = "!git add -A && git commit -m "
wip = "!git add -A && git commit -m 'WIP commit - quick save'"
amno = "!git add -A && git commit --amend --no-edit"
amend = "!git add -A && git commit --amend"
work = !git lg --author \"YOUR_NAME_HERE\" --before today --after \"five days ago\" --no-merges
info = !git st && echo && git lo && echo && git remote -v
# Handling files that are to be assumed unchanged.
ignore = update-index --assume-unchanged
uningore = update-index --no-assume-unchanged
ignored = !git ls-files -v | grep '^[a-z]'
# Branches
p = "!git push origin $(git rev-parse --abbrev-ref HEAD)"
rr = "!git fetch --all && git rebase origin/master"
n = "!git checkout -b"
co = "!git checkout"
st = "!git status"
rv = "!git checkout --"
cleanup = "!git reset --hard && git clean -f"
# Stashes
isl = "!git stash list"
sa = "!git stash apply"
ss = "!git stash save"
# Diffs
dt = difftool --no-prompt
mt = mergetool --no-prompt
# Tags
lstags = "!f(){ echo 'Describe: '; git describe; echo 'Latest 5 tags: '; git tag | sort -V | tail -5; }; f"
colt = "!f(){ local latest=`git tag | sort -V | tail -1`; git checkout $latest; }; f"
# Read aliases
alias = "config --get-regexp 'alias.*'"
[merge]
tool = meld
Some additional tweaks
Senior Java software engineer and mentor
1 年Nice article! I noticed that you mentioned creating Git and Maven aliases. Have you considered leveraging existing Oh My Zsh plugins for Git and Maven? They can simplify the process for you. https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/mvn https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/git
Business Manager at TMC
1 年Turtle power