Today I Learned

A Hashrocket project

104 posts by doriankarter @dorian_escplan

Write into a protected file without reopening Vim

If you ever worked on an SSH session on a remote machine and tried to edit a file that requires super user permissions you might be familiar with the following scenario:

  1. You open the file in vim (e.g. nginx.conf)
  2. You make a few changes, potentially many
  3. You are happy with the result and run the write command :w
  4. You get an error saying that the file is readonly or that you don’t have permissions to write to it
  5. Now you are scrambling to copy all your changes and save them somewhere else
  6. Then you re-open the file with sudo vim ... paste your changes and save. Hopefully everything went smoothly and you did not lose your changes.

No more! Next time this happens try this:

:w !sudo tee %

I hope it saves you some frustration.

Execute a shell command on every commit in rebase

Git rebase allows you to execute a command on any commit in a rebase:

git rebase -i -exec "git reset-authors"

The result will look something like this:

pick xxxyyy Do stuff to things
exec git reset-authors
pick yyyzzz Do things to stuff
exec git reset-authors

It is very useful for resetting authors on multiple commits in case you forgot to set the current pair.

P.S. if you are curious about what git reset-authors does check out our .gitconfig in Hashrocket’s dotfiles:

reset-authors = commit --amend --reset-author -CHEAD

Bypass aliases with the `command` command

If you are writing a bash script to be used by others and you call external dependencies you might encounter a situation where a user has defined an alias in place of the original command.

For example users of the hub command line utillity may have an alias

alias git='hub'

Or something more practically challenging:

alias grep='grep  --color=auto --exclude-dir={.bzr,CVS,.git,.hg,.svn}'

If your command relies on the output of the original program without unexpected modifications you need a way to bypass the aliases and call the command directly.

To bypass aliases prefix the original program call it with the command command. For example:

command git --no-pager diff | command grep '[something]'

I like to think of it as the bash equivalent of Vim’s noremap.

Repeatable operations on search matches with gn

When you find yourself having to operate on a certain string, you may first search for it:


To change it you will usually use a repeatable operation such as ciw followed by whatever you are changing it to.

Now to repeat that change you will first jump to the next search result using n then press the . operator to repeat the change. But if you know that you are going to do that there’s an easier way:

Instead of ciw use cgn. Then just press the . and Vim will jump to the next match and change it for you.

According to Vim’s help:

gn - Searches forward for the last used search pattern, like with n, and starts Visual mode to select the match.

for more info:

:h gn
:h gN (for searching backwards)

Note: this also works with * which searches for the word currently under the cursor.

Create a directory and cd into it with one command

I don’t know about you but I tend to create directories from terminal often, and when I do, cding into them is the first thing I’ll do after creating the directory.

This is what it usually looks like

mkdir -p foo/bar/baz
cd foo/bar/baz

This can get quite verbose. You may have also tried this pro tip:

mkdir -p foo/bar/baz
cd !$ # press <TAB> to expand !$ to the last argument of the previous command

But I think this can be even simpler and easier. Add the following to your .zshrc or .bashrc:

mkcd() {
  mkdir -p $1 && cd $1

Now source .zshrc/.bashrc and simply run:

mkcd foo/bar/baz


Word Count in Vim

Vim has a built in shortcut for counting words. To see the word count for the whole buffer type:


You will see something like:

Col 11 of 54; Line 12 of 24; Word 39 of 68; Byte 360 of 727

Meaning we are currently at word 39 and the whole buffer contains 68 words.

To see the word count for a selection, first select and type the same shortcut g<CTRL-g> the result should look something like this:

Selected 7 of 24 Lines; 23 of 68 Words; 234 of 727 Bytes

in this case I have selected 23 words.

Save harddrive space by using git shallow clones

Sometime you clone starter projects, libraries, or plugins to help you get started on a new project or POC.

Perhaps you are using git clone to get your project on a remote server.

When you clone a project what you also get is all the previous states of that repository at each commit. This can add up fast and take a good chunk of your hard drive space as well as take long to download and decompress.

To solve this you can clone a shallow copy of the repository by using the depth switch on the git clone command, and providing it with the value of 1.

git clone --depth 1

Use Vim counts for small arithematic calculations

In CSS land you often need to increment/decrement a pixel value. You can use <C-a> for incrementing and <C-x> for decrementing value but what if you want to move faster or increment by a specific number?

Counts for the rescue!

Every motion in vim can be preceded by a count, and as it turns out so does increment/decrement:

body {
  height: 1827px;

Say I want to increment the padding by 344. I can either:

  • replace the 1827 with 2171 after using my calculator.
  • Press <C-a> 344 times
  • Or alternatively 344<C-a>

You can also set a mapping to increment/decrement by 10.

Credit: Practical Vim by Drew Neil

Add highlighted code from #Vim to #Apple #Keynote

Giving a talk with keynote? If you’re like me and you love Vim and Apple Keynote you might struggle with getting your highlighted, indented code over to Keynote and making it look as good as it looks in Vim.

Fret no more - vim-copy-as-rtf is a plugin that will let you do that without installing any additional libraries on your mac.

Simply select the code snippet, type :CopyRTF and the highlighted code will be copied to your clipboard ready to be pasted into Keynote. That simple.

Get it here:

Types and type casting in #PostgreSQL

To see the type of column or any entity in PostgreSQL use pg_typeof. Here’s an example:

select pg_typeof(array['thing']);


-- pg_typeof
-- ---------
-- text[]

To cast to another type use the :: operator:

select pg_typeof(array['thing']::varchar[]);


--      pg_typeof
-- -------------------
-- character varying[]

h/t Josh Branchaud

Persistent folds between Vim sessions

Folds are great. They help you when you have to deal with big files where compartmentalizing the logic might be of help.

The problem is that when you close Vim, your artfully folded code returns to its unfolded state.

The solution is quite simple - when you are ready to save your folds run the :mkview command. This will save your folds in the current buffer to your viewdir (:h viewdir) depending on your environment.

To load your folds use :loadview.

To automate this process add the following to your vimrc:

augroup AutoSaveFolds
  autocmd BufWinLeave * mkview
  autocmd BufWinEnter * silent loadview
augroup END

The folds will be local to your machine, but if you want you can configure mkview to save folds to a file in your project directory and share them with your team.

Homebrew is eating up your harddrive

If you’ve been using Homebrew on your Mac (if you have a Mac you really should) you may not be aware that every time you upgrade your brew formulas using brew update && brew upgrade Homebrew is leaving behind a copy of the old versions.

With package updates becoming available daily you may end up with gigabytes of space being wasted away on old package versions.

To see how much space the old versions are using run brew cleanup -n. When I ran that command I got:

==> This operation would free approximately 9.2G of disk space.

Holy cannoli! zomg

If you feel like reclaiming that diskspace just run the command again without the -n: brew cleanup.

Enjoy space! 🚀

Find where anything is defined in Vim config

When your vim bundle and vimrc become a plugin soup you often need to debug where an autocmd, command, map or function are coming from.

The :verbose command can come in handy in this scenario. Here are some examples:

See where a mapping was set from:

:verbose map gY

See what happens when you enter a buffer:

:verbose autocmd BufEnter

See which file defined a command:

:verbose command Explore

Where is the abbreviation coming from:

:verbose abbrev bpry


Example output:

    Name        Args       Address   Complete  Definition
!   Explore     *    0c              dir           call netrw#Explore(<count>,0,0+<bang>0,<q-args>)
        Last set from /usr/local/Cellar/vim/7.4.1190/share/vim/vim74/plugin/netrwPlugin.vim

Happy hunting! 🔫

Browse and repeat Vim commands

If you typed a command in Vim’s command line and want to repeat it you can open the command-line window and browse through past commands. There are two ways two do that:

  1. From Normal mode type q:
  2. From the command line after typing a colon press CTRL-f

In the command window you can browse up and down with HJKL and hit return to re-run the command.

Missed an alert message in vim?

If you ever missed an alert message in Vim, you know the ones that show up at the bottom in the command line, you can easily view a list of all past messages by running the :messages command.

You can also add your own using :echom, which adds a persistent message.

Try it now.

NOTE this will only show persistent messages (echom), and not momentary messages set using echo.

Highlight #markdown fenced code syntax in #Vim

Up until now I was editing all my blog posts in Atom for lack of markdown fenced code block highlighting in Vim. Atom supported it out of the box. As it turns out Vim can do that too, out of the box!

If you are running a recent version of Vim (mine at time of writing 7.4.9910) you can setup highlighting for fenced code blocks in markdown.

Open your .vimrc and add the following line:

let g:markdown_fenced_languages = ['html', 'vim', 'ruby', 'python', 'bash=sh']

You can customize it to your liking and add more languages.

Note: Not all languages are supported but you can try and see if they work. To see a list of languages you have installed on Mac (with Vim installed by Homebrew) run ls -l /usr/local/Cellar/vim/7.4.1190/share/vim/vim74/syntax


This is a game changer.

Breezy copy to system clipboard in Vim

When it’s time to get text processed in Vim out of your editor and onto a shiny blog post many Vim Warriors reach for the awkward “copy to system register” keyboard chord.


Worse is trying to copy the whole file:


This feat of keyboard heroism has crushed many heroes and inflicted countless RSI wounds.

It’s time to slay the dragon 🐲 by adding these to your .vimrc:

" copy to system clipboard
map gy "*y
" copy whole file to system clipboard
nmap gY gg"*yG

Pretty Print JSON/HTML in Vim

When working with external APIs often you will get a highly netsted json, like this one, all in one line, with no spaces:

{"batters":{"batter":[{"id":"1003","type":"Blueberry"},{"id":"1004","type":"Devil's Food"}]},"id":"0001","name":"Cake","ppu":0.55,"topping":[{"id":"5002","type":"Glazed"},{"id":"5007","type":"Powdered Sugar"}],"type":"donut"}

The horror. You are not a network cable! You deserve better!

Add the following to your .vimrc file:

command! PrettyPrintJSON %!python -m json.tool
command! PrettyPrintHTML !tidy -mi -html -wrap 0 %
command! PrettyPrintXML !tidy -mi -xml -wrap 0 %

Now you can paste the json into your Vim buffer and run the :PrettyPrintJSON command.

    "batters": {
        "batter": [
                "id": "1003",
                "type": "Blueberry"
                "id": "1004",
                "type": "Devil's Food"
    "id": "0001",
    "name": "Cake",
    "ppu": 0.55,
    "topping": [
            "id": "5002",
            "type": "Glazed"
            "id": "5007",
            "type": "Powdered Sugar"
    "type": "donut"


Same goes for HTML, just run :PrettyPrintHTML.

NOTE: For these to work you need to have python and tidy installed on your machine.

Change Rails validation message completely

Rails always appends field name to validation messages, and when setting message: on a validation statement it gets appended to the humanized name of the field.

If you want to change the validation message completely use the locales file:

# config/locales/en.yml
        email: "E-mail address"
              blank: "is required"

This was particularly useful with the ValidatesTimeliness gem which does not support a lambda.

🎉Happy 500 post to TIL 🎉

Set custom user agent on #Capybara

Sometimes you want to emulate a request to your site from a device with a specific user-agent. This is particularly useful if you have a different behavior when users use those devices (e.g. wrapped mobile app using Cordova)

Setting the user agent can be accomplished by setting the header on the current session:

Capybara.current_session.driver.header('User-Agent', 'cordova')

Custom order #Postgres #SQL union queries

Consider the following data:

insert into users (email, first, last) values ('', 'New', 'User');
insert into users (email, first, last) values ('', 'Lemmy', 'Kilmister');
insert into users (email, first, last) values ('', 'Lemmy', 'Kilmister');

Assuming you want to match a user to the following data:

{ email: '', first: 'New', last: 'User' }

And you consider email a better indication of a match, and first and last name are a fallback. The following query will not yield the desired results despite the `where` conditions being ordered per the requirements:

select * from users where email = ‘’ or (first = ‘New’ and last = ‘User’) limit 1;

This will result in:

1 | ‘’ | ‘New’ | ‘User’

To find by email first we will need to union two queries, rank the match then order by rank:

(select 1 as rank, id, email, first, last from users where email = ‘’) union (select 2 as rank, id, email, first, last from users where first = ‘New’ and last = ‘User’) order by rank limit 1;

This will yield the correct result:

3 | ‘’ | ‘Lemmy’ | ‘Kilmister’

How to use the hidden #VNC client in #Mac #OSX

OS X has a built in VNC (Screen Sharing) server, but it is a little known feature that it also has a built in VNC client. No additional software is necessary.

To setup the server go to Preferences->Sharing and check the “On” checkbox next to “Screen Sharing”. Make sure to only allow access to Administrators or a specific user/user group.

Screen Sharing

You should see your computer name on the Screen Sharing configuration screen. To connect to your computer from another one using VNC open Finder and press ⌘+k. In the Server Address enter vnc:// followed by your computer name or IP address. Connect To Server

h/t Dillon Hafer

Check if a #ruby gem is installed from bash script

If you are adding customizations to your zshrc, such as adding auto completion for a certain gem, you want to make sure that the gem is installed before performing any action.

The gem list [gemname] -i command returns a boolean representing whether a gem is installed or not.

if `gem list lunchy -i`; then 
  echo "Lunchy gem is installed!"; 
  # do some configuration here

If you wish to be more granular you can check whether a specific version is installed by adding the --version [version] flag.

if `gem list lunchy -i --version 0.10.4`; then 
  echo "Lunchy v0.10.4 is installed!"; 
  # do some configuration here

Quickly edit and reload #tmux configuration

When you are playing around with your tmux config you often need to repeatedly open .tmux.conf file and then source it into the current tmux session.

To make things a little faster, add the following to your .tmux.conf:

bind-key r source-file ~/.tmux.conf \; display-message "~/.tmux.conf reloaded"
bind-key M split-window -h "vim ~/.tmux.conf"

Now you can quickly open the tmux config in tmux pane using <prefix> followed by shift + M, edit your configuration, and save when you done. To reload the tmux configuration use <prefix> followed by r.

** <prefix> is C-z for hashrocket’s dotfile project (dotmatrix), if you are using tmux default configuration it would be C-b

Fix Tmux 2.1 mode-mouse error

If your tmux started displaying the following error message:

/Users/username/.tmux.conf:136: unknown option: mode-mouse
/Users/username/.tmux.conf:137: unknown option: mouse-select-pane
/Users/username/.tmux.conf:138: unknown option: mouse-resize-pane
/Users/username/.tmux.conf:139: unknown option: mouse-select-window

when you launch it, it is because the tmux 2.1 has a new syntax for turning mouse-mode on. All of the above are now combined into:

set -g mouse on

You’ll also notice that after replacing the mouse mode setting with the new one in your config you still cannot scroll up/down with your mouse wheel. To fix that use the following configuration:

bind -n WheelUpPane   select-pane -t= \; copy-mode -e \; send-keys -M
bind -n WheelDownPane select-pane -t= \;                 send-keys -M

See the source and location for bash commands

The oh-my-zsh package comes with a lot of useful plugins. Often those plugins add bash functions to the global scope.

If you want to see where the function is defined you can use the type command.

For example the new_gh/exist_gh command which creates a remote repo for a folder

$ type exist_gh
exist_gh is a shell function from /Users/dkarter/.oh-my-zsh/plugins/github/github.plugin.zsh

To see the function source use the declare command:

$ declare -f new_gh
new_gh () {
        cd "$1"
        ghuser=$( git config github.user )
        git init
        print '.*'"\n"'*~' >> .gitignore
        git add ^.*
        git commit -m 'Initial commit.'
        git remote add origin${ghuser}/${repo}.git
        git push -u origin master

Change Vim cursor in different modes

Vim’s NORMAL mode and VISUAL mode are complemented perfectly by the block cursor. When in INSERT mode however, you might want a little more precision. That’s why changing the cursor to a slim pipe shape is beneficial (you know, like in any textbox on your OS). It is also a nice reminder that you are in VISUAL mode, without having to stare at the bottom of the screen.

While we are at it, you might also want REPLACE mode to have a cursor of it’s own, for that an underscore style looks great.

To accomplish this customization add the following to your .vimrc

iTerm2 + Tmux on OS

let &t_SI = "\<Esc>Ptmux;\<Esc>\<Esc>]50;CursorShape=1\x7\<Esc>\\"
let &t_SR = "\<Esc>Ptmux;\<Esc>\<Esc>]50;CursorShape=2\x7\<Esc>\\"
let &t_EI = "\<Esc>Ptmux;\<Esc>\<Esc>]50;CursorShape=0\x7\<Esc>\\" 

iTerm2 on OS

let &t_SI = "\<Esc>]50;CursorShape=1\x7"
let &t_SR = "\<Esc>]50;CursorShape=2\x7"
let &t_EI = "\<Esc>]50;CursorShape=0\x7"

Vim startup time profiling

If you want to see why vim is taking so long, you can get a breakdown of how long each plugin took to load:

vim --startuptime startup.log

To make things a little easier, I created the following bash command, which will create the startup log, open it in vim and delete it when done.

vim --startuptime startup.log +qall && vim startup.log && rm startup.log

Graphing the data

You can use vim-plugins-profile shell script to get a better sense of which plugins are causing the biggest slowdown:

It will create a graph resembling the DevTools network tab: graph

and provide a summary similar to this one:

Generating vim startup profile...    
Parsing vim startup profile...     
Crunching data and generating profile plot ...    

Your plugins startup profile graph is saved     
as `profile.png` under current directory.    

Top 10 Plugins That Slows Down Vim Startup    
   1    105.13  "vim-colorschemes"    
   2    42.661  "vim-easytags"    
   3    31.173  "vim-vendetta"    
   4    22.02   "syntastic"    
   5    13.362  "vim-online-thesaurus"    
   6    7.888   "vim-easymotion"    
   7    6.931   "vim-airline"    
   8    6.608   "YankRing.vim"    
   9    5.266   "nerdcommenter"    
  10    5.017   "delimitMate"    

Profiling Vim

To find which plugins may be causing certain actions in vim run slowly try using the built in profiler:

:profile start profile.log
:profile func *
:profile file *

Then perform the slow action, when done run:

:profile pause

You can then open the profile.log file and look at the bottom to see summary, sorted by run time, of which functions took the most time, the function name may give away which plugin/core function is causing the issue. The top of the file will contain each line of code that was run in vim during the profiling session and how long it took.

Chrome DevTools navigation and editing tools

If you ever worked with editors such as Atom/Sublime Text you will appreciate the following: Chrome DevTools now sports fuzzy finders for your script/stylesheet files and for methods within them.

To get started open dev tools and hit Cmd+p start typing a filename or part of a filename: cmd-p

Then to jump to a specific method hit Cmd+Shift+P and start typing a method name: cmd-shift-p

If you are a big fan of multiple cursors, you’ll be happy to learn that those are now available within chrome developer tools:

cmd-d [while the cursor is on a word hit Cmd+d to duplicate the cursor to the next match]

holding alt [holding alt and dragging down will allow you to edit a vertical line]

To search all files (scripts/html markup) hit Cmd+Option+f: cmd-alt-f

Change the source in dev tools and hit Cmd+s the updated code will be run the next time it is called. DevTools will indicate it has a modified version by changing the background color to bright orange: change in memory

Using awk to debug $PATH

If you ever tried printing your system PATH environment variable using echo $PATH you probably got something like this:


Not a pleasant read.

I thought that would be a good opportunity to practice my awk scripting skills and came up with this:

echo $PATH | awk '{ n = split($0, paths, ":"); for (i=0; ++i <= n;) print i, paths[i] }'

It prints a numerically indexed list of the paths and prints them in separate lines.

1 /usr/local/heroku/bin
2 /usr/local/bin
3 /Users/username/.rvm/gems/ruby-2.2.2/bin
4 /Users/username/.rvm/gems/ruby-2.2.2@global/bi
5 /Users/username/.rvm/rubies/ruby-2.2.2/bin
6 /usr/local/bin
7 /usr/bin
8 /bin
9 /usr/sbin
10 /sbin
11 /opt/X11/bin
12 .git/safe/../../bin
13 /Users/username/.bin
14 /usr/local/sbin
15 /Users/username/.rvm/gems/ruby-2.2.2/bin
16 /Users/username/.rvm/gems/ruby-2.2.2@global/b
17 /Users/username/.rvm/rubies/ruby-2.2.2/bin
18 /Users/username/.rvm/bin
19 /Users/username/.rvm/bin
20 /Users/username/Dropbox/Developer/gocode/bin

You can alias this command if you use it often:

alias print-path=`echo $PATH | awk '{ n = split($0, paths, ":"); for (i=0; ++i <= n;) print i, paths[i] }'`

You may want to check out another rocketeer’s (Josh Branchaud) solution to this problem, written in Rust:

vim-surround is different for selected text

If you tried using vim-surround after selecting text in visual mode, just to get your text deselected and have nothing happen, it’s because visual mode uses a different trigger for vim-surround:

In visual mode use S, followed by your surrounding character (e.g. S)).

This is different from the normal mode way of doing it ys[text-object] (e.g. ysap{)

I like thinking of this one as “yes, surround! [my text object]” and prefer it to selecting, but some cases require visually selecting.

Kill process by name

While killing processes using their PID isn’t hard, the process can be simplified further. You can kill a process by its name.

This is how you do it using PID:

ps aux | grep [process_name]
# copy the pid from the output
kill [PID] # paste pid

This is how it’s done using the name of the process:

pkill [process_name]
# e.g. pkill rails

Spell check in vim

Don’t let typos sneak into production, you can use a spell checker right from Vim. Here’s how:

:set spell

To navigate between spelling mistakes use ]s and [s.

To correct spelling mistakes, go to the mistake and use z= to see suggestions.

P.S. if the spelling errors don’t show up, make sure to check two things:

  1. That you are not a fantastic speller and a true scholar
  2. That the file type you are checking spell on is allowed (you can test it by setting your syntax to txt :set syntax=txt)

Find (and kill) all processes listening on a port

To search for processes that listen on a specific port use the lsof or “List Open Files”. The -n argument makes the command run faster by preventing it from doing a ip to hostname conversion. Use grep to show only lines containing the word LISTEN.

lsof -n | grep LISTEN

To filter for a specific port use the following:

lsof -n -i4TCP:[PORT] | grep LISTEN

To kill all processes listening on a specific port use:

lsof -n -i4TCP:[PORT] | grep LISTEN | awk '{ print $2 }' | xargs kill

The awk command returns only the second column (PID), and the xargs executes kill on each line returned.

Add colour to your man pages

Syntax highlighting makes a programmer’s life more cheerful. Linux man pages shouldn’t be an exception.

Add the following to your zshrc to highlight arguments and commands in man pages:

export LESS_TERMCAP_mb=$(printf '\e[01;31m') # enter blinking mode – red
export LESS_TERMCAP_md=$(printf '\e[01;35m') # enter double-bright mode – bold, magenta
export LESS_TERMCAP_me=$(printf '\e[0m') # turn off all appearance modes (mb, md, so, us)
export LESS_TERMCAP_se=$(printf '\e[0m') # leave standout mode
export LESS_TERMCAP_so=$(printf '\e[01;33m') # enter standout mode – yellow
export LESS_TERMCAP_ue=$(printf '\e[0m') # leave underline mode
export LESS_TERMCAP_us=$(printf '\e[04;36m') # enter underline mode – cyan


Browse ruby gem source inside of a vim tab

When you are working with gems you often need to jump to the gem’s source. Vim has a really neat trick for that.

First make sure you have the vim-bundler plugin by Tim Pope installed: Then you can use the following command:

:Btabedit name_of_gem


Vim opens the gem’s source starting with a netrw file list in a new tab for you.

Bonus: Vim will autocomplete the gem name for you based on your Gemfile.

Never leave the home row in bash

To edit a command in bash you often need to jump around in the line and revert to using the arrow keys. As a vim/emacs user this becomes a bit of a clumsy non-ergonomic movement, here are some shortcuts to help you keep your fingers on the home row. If you are an emacs user these are going to look familiar.

  • ctrl-p - previous command entered
  • ctrl-n - next command entered
  • ctrl-a - jump to BOL
  • ctrl-e - jump to EOL
  • alt-b - jump word forward
  • alt-f - jump word backwards
  • alt-b - jump character forward
  • alt-f - jump character backwards

If these shortcuts don’t work try running set -o emacs

Alternatively you can turn on vi mode in your shell by calling set -o vi, which you can add to your .zshrc or add set editing-mode vi to your .inputrc. After setting this you can enter normal mode by hitting escape and use vi motions to edit/move.

Your shell just got upgraded. 💪💻

Use `watch` to monitor status commands in bash

If you need to monitor a status command such as monit status or service nginx status, instead of calling the command over and over use the watch command:

watch monit status

by default it will refresh the status every 2 seconds and highlight changes as they occur. You can modify the interval by using the -n switch:

watch -n 1 monit status

If your status command uses color you can turn it on by using the -c switch.

P.S. If you need to run this command on mac you will need to install the watch package using homebrew.

Use bash's Bang command to improve productivity

Bash has neat way to repeat last ran command. In your shell type !! this will put the last ran command in your prompt and allow you to edit and execute it. Use it to add sudo to any command:

$ apt-get install somepackage
Insufficient permissions
$ sudo !!
$ sudo apt-get install somepackage

If you want to go back to a specific command other than the last you have a few options:

You can execute a history command by its ID (to see all IDs run history, to clean history history -c)

$ history
1234 some really long command
1236 third command
$ !1234
$ some really long command
$!-2 # run two commands ago (not including bang commands)
$ history

You can run the last command containing a specific string:

$ foo bar
$ bar foo bazz
$ !foo # last command starting with foo
$ foo bar
$ !?bazz # last command containing the word bazz
$ bar foo bazz

Reuse last/first argument:

$ ls -la /development/reallylongnameidontwanttoretype
$ cd !$
$ cd -la /development/reallylongnameidontwanttoretype
$ $^ app
$ cd app