Bash Tips (@bashtips) profile picture

Handy tips and tricks for bash. Got suggestions? @bashtips them to us

/bin/bash
Joined July 2009
*tap tap* Is this thing still on? Looks like we should start posting tips again. If you'd like to help out, say hello!
4
1
1
Need to run a command on multiple servers simultaneously? alias dsh="cat ~/nodes.txt | xargs -P0 -I NODE ssh NODE -C"
1
2
9
Adding bind '"\e[A"':history-search-backward and bind '"\e[B"':history-search-forward to .bashrc makes your up/down keys autocomplete.
4
5
Use ~-/ to refer to the last directory you were in: "cd woo/; cd ../yay/; cp ~-/foo.txt .;" will copy foo.txt from woo/ to yay/
1
6
10
M-. inserts/cycles through the last argument from previous commands.
2
Use C-v [KEY] to insert a literal character. E.g. C-v [TAB] to insert a tab rather than auto-completing - useful when grepping logs.
1
1
!* inserts all the arguments from the previous command.
2
2
Add "shopt -s checkwinsize" to your .bashrc to make sure terminals wrap lines correctly after resizing them.
7
1
12
Use bash expansion when cp/mv'ing: `cp file{,.bk}` to create "file.bk", `mv file{.bk,}` to replace "file" with "file.bk"
3
Insert the last argument of the previous command: !!$. Eg: `touch foo; ls -la !!$` (From @zigdon)
1
1
Add "shopt -s cdspell" to your .bashrc for small typos to be automatically corrected when changing directory.
3
1
curl -u <username> http://teapawt.org/statuses/update.xml -d status="Tweet from the cmd-line without exposing your password in history"
1
2
1
3
(oops, the original examples should be ^foo^bar and !!:gs/foo/bar, for that output, sorry)
Both replace terms in the last cmd run, so if you'd just run "echo foofoo" the output would be "barfoo" and "barbar" respectively.
Someone asked the difference between ^foofoo^bar and !!:gs/foofoo/bar? The former only replaces the first match, the later all matches.
1
2
Add "set completion-ignore-case on" to your .inputrc to make tab-completion case insensitive.
2
9
Add "shopt -s histappend" and "export PROMPT_COMMAND='history -a'" to your .bashrc and your command history will be saved for all terminals.
7
8
Repeat the entire last command with "!!", handy for running the last command as root, for example "sudo !!"
3
3
Add "bind Space:magic-space" to your .bashrc and any ! combinations will be auto-expanded when you hit space.
3
3
Perform a regex replace on the last command and execute the result, eg !!:gs/foo/bar turns "ls foo" into "ls bar".
1
1