Useful shell shortcuts

Reference

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 http://weather.yahooapis.com/forecastrss?p=98117
=> 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
...
!rak
=> Runs 'rake test:recent' or last command starting with 'rak'

Sets

{a,b} (A set)

How often do 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'

0 Responses to “Useful shell shortcuts”



  1. 댓글 남기기

댓글 남기기

아래 항목을 채우거나 오른쪽 아이콘 중 하나를 클릭하여 로그 인 하세요:

Gravatar
WordPress.com 로고

WordPress.com의 계정을 사용하여 댓글을 남깁니다. Log Out / 변경 )

Twitter picture

Twitter의 계정을 사용하여 댓글을 남깁니다. Log Out / 변경 )

Facebook 사진

Facebook의 계정을 사용하여 댓글을 남깁니다. Log Out / 변경 )

%s에 연결하는 중





팔로우

Get every new post delivered to your Inbox.

Join 39 other followers