My 5 Favorite Shell Shortcuts
Join the DZone community and get the full member experience.Join For Free
I love shortcuts. I do my best to learn keyboard shortcuts, I setup aliases, and I like using anything that makes things faster. Here are a few of my favorites for a shell in Linux or OS X. These aren’t ninja shell moves that folks who’ve been doing this for a while will not know – these are basic shortcuts that everyone should know.
I use this shortcut every single day when working in bash or zsh. This takes the last argument of the previous command and uses it wherever this variable is used. Here is an example:
Copy a file & then edit the new file.
$ cp file-a file-b $ vim !$
If you are a zsh user you can take this one further and reference specific elements of the previous command using !! where is the element you want to reference:
~/> touch this that the other thing ~/> ls !!2 ~/> ls that that
The indexes start with 1.
2) grep -ri
I’m sure a bunch of you are thinking “Seriously?” and I would have too until a week or so ago when I watched someone type this:
$ grep */*/*/*
I asked what the hell they were doing, they said they were checking the files under each directory (they kept adding asterisks for each level). This person wasn’t Jr, but was used to other operating systems that didn’t have a recurse option. Modern operating systems with any respectable utility have a -r (recurse) option, you should use it.
The -i argument makes it case insensitive.
3) cd -
This will take you back to the directory you were in previously. There are lots of other tricks with ‘cd’ but this is one I use all the time.
Lets say you are deep in some directory and need to hop to another directory quickly:
[/usr/share/fonts/dejavu]$ cd /var/log [/var/log]$ cd - /usr/share/fonts/dejavu [/usr/share/fonts/dejavu]$
4) Reverse i-search
At least in bash & zsh, typing Control-R will allow you to search as you type through your history. This is really handy when you know the start, middle, or end of a command but aren’t sure what the rest is. Try it, type Control-R and start to type a command you’ve typed previously – once you find the one you want, just edit it (or not) and go.
If you aren’t building aliases then you are missing out on one of the oldest shortcuts here. An alias allows you to define a command which calls another command. I make very heavy use of these and I see plenty of people who don’t.
alias vipuppet='cd ~/projects/puppet ; mvim .'
Opinions expressed by DZone contributors are their own.