Monday, March 24, 2008

Collection of Bash Tips

I ran across a selection of bash tips at http://www.shell-fu.org/lister.php?top. Many of them are very specific but here are a few that seem to come up daily:

Using expansion to move a file aside without having to type the file name twice

> cp ReallyLongFileNameYouDontWantToTypeTwice{,.orig}


Running a second command with the same arguments as the previous command, use '!*' to repeat all arguments or '!:2' to use the second argument. '!$' uses the final argument.
> cd /home/user/foo
cd: /home/user/foo: No such file or directory
> mkdir !*
mkdir /home/user/foo


Don't search history by grepping
~/.bash_history, or repeatedly hitting the up arrow, instead use CTRL+r (or '/' in vi-mode) for search-as-you type. You can immediately run the command by pressing Enter.

Make a whole directory tree with one command
Use the -p option to mkdir and make all parent directories along with their children in a single command.
>mkdir -p tmp/a/b/c


Use history to SUDO last command
Forget that your running as underprivileged? No need to retype the command.
> rpm blah
Permission denied
> sudo !!


Bash fork bomb
Don't forget the bash fork bomb. DO NOT TRY THIS AT HOME... Posted here so that you don't see this in a forum or a mailing list and use it without knowing:
>:(){ :|:& };:


Explanation:
:()
defines a function called : (accepts no arguments)
{ :|:& };
This is the function: It calls the function itself and pipes the output to the same function ":" and puts the process in the background. (Recursive invocation) with ; it ends the function definition
:
Calls the function and creates havoc.

Use ALT+. to insert last parameter
In bash (or anything using libreadline, such as mysql) press ALT+. to insert the last used parameter from the previous line.
Ex:
> vim some/file.c
> svn commit


Selected Bash Keystrokes:
Ctrl-U - Cuts everything to the left
Ctrl-W - Cuts the word to the left
Ctrl-Y - Pastes what's in the buffer
Ctrl-A - Go to beginning of line
Ctrl-E - Go to end of line

No comments: