Sunday, May 27, 2007

Useful Shell Shortcuts

from Nuby on Rails by topfunky

A few weeks ago someone asked me to recommend a few useful books on Ruby. The first one? Using csh & tcsh. I spend a lot of time in the terminal and these shortcuts help in both tcsh and bash.
Reuse previous arguments

The ! operator gives you a quick way to refer to parts of the previous command.
!! (Full contents of previous command)

How many times have you tried to edit a file, then realize that you need to be root to do it? Use bang-bang to quickly repeat the previous command, with other commands before or after.

emacs /etc/init.d/mongrel_cluster
=> Permission Denied
sudo !!
=> Now opens the file as root

!$ (Last arg of previous command)

Sometimes I need to reuse the last argument with another command, like here where I forgot to quote a string.

=> wget: No Match
wget '!$'
=> Now it works

!^ (First argument of previous command)

I rarely use this, although it could have been used in the previous tip.

echo fish and chips
echo !^
=> fish # First argument

!:1 (Argument by number)

!:1 is the same as !^. The difference is that you can reference any element of the previous command.

echo fish and chips
=> fish and chips
echo !:1
=> fish # Same thing as !^

echo fish and chips
echo !:2
=> and # Word 2 in previous command, zero-indexed

echo fish and chips
echo !:0
=> echo # The very first word in the previous command

echo fish and chips
echo !:1-3
=> fish and chips # A range

!pattern (Repeat last command in history with pattern)

The bang is useful for re-running a command that you’ve run before. Spell out the first few letters and hit ENTER (or TAB to show the completion in tcsh). The shell will search backwards in your history until it finds a command that starts with the same letters.

I like the tcsh behavior since you can hit TAB to see what you’re asking for. Using this in bash can be more adventurous since you don’t know what command will be run until you hit ENTER.

rake test:recent
=> Runs 'rake test:recent' or last command starting with 'rak'

{a,b} (A set)

How often to you rename just part of a file? The {} syntax is convenient.

mv file.{txt,xml}
=> Expands to 'mv file.txt file.xml'

mv file{,.orig}
=> Expands to 'mv file file.orig'

mkdir foo{1,2,3}
=> Expands to 'mkdir foo1 foo2 foo3'

Mac OS X-specific
pbcopy and pbpaste

In Mac OS X, you can copy things to the clipboard and read them back out. This is nice because you can reuse it in the shell or back in the OS with Apple-C or Apple-V.

./generate_random_password | pbcopy

pbpaste > file.txt

No comments :