My Favorite bash Tips and Tricks
$ echo {one,two,red,blue}
one two red blue
Usando um echo simples eu obteria o mesmo resultadoecho one two red blueMas protegendo uma lista entre chaves eu obtenho mais que isso, veja:
$ echo fish{one,two,red,blue}
fishone fishtwo fishred fishblue
$ echo {"one ","two ","red ","blue "}fish
one fish two fish red fish blue fish
Using !?text?
This will execute the most recent command that contains the word ‘text’. Example:
debian$ !?xjf?
tar -xjf hedgewars-src-0.9.14.1.tar.bz2
tar: hedgewars-src-0.9.14.1.tar.bz2: Cannot open: No such file or directory
Alternando entre opções (tab completion)
# coloque no seu ~/.inputrc # o tab completion será ativado # com alternativas usando o atalho Ctrl-i
"\C-i": menu-complete
$ cp /etc/httpd/conf/httpd.conf{,.bak}
Gerando backup de um arquivo
$ cp /etc/httpd/conf/httpd.conf{,.bak} Obs: Se você usar somente a vírgula ele imprime o nome duplicado veja... echo nome{,.sufixo} agora faça: echo nome{,.bak}
Essa abordagem (usando a expansão de variáveis) é também usada quando usamos o comando
mkdir para criar uma extutura completa de pastas:
mkdir -p docs/{img/{fotos,icons,wallpapers,svg},textos/{artigos,man},tmp} A regra aqui é a seguinte: para cada pasta que conterá subpastas use "nome/{}" dentro das chaves coloque os nomes separados por vírgula e não esqueça de usar o parâmetro '-p' no começo do comando!
O Bash simplesmente cria o arquivo 'bak' no caminho indicado sem a necessidade de fazer algo como:
$ cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf.bak
O comando cp tem ainda um jeito legal para fazer backups, no qual ele preserva
as permissões, não desreferencia links simbolicos e apenas escreve o que for mais recente.
cp -uvfa /origem /destino
- u - update
- v - verbose (detalhado)
- f - força
- a - Equivale às opções -dpR do cp
Formatando a data de um jeito mais simples:
$ date +%d-%b-%Y 12-Mar-2004 Outra possibilidade --> echo $(date +%T)Repetindo o argumento do comando anterior
ls -l /etc/passwd
vim alt-.
Na verdade o alt-. vai alternando etre agumentos dos
ultimos comandos
# pode-se usar em scripts algo assim
wget -c http://link-para-arquivo -O nome-a-ser-atribuido && chmod 700 $_
# o cifrão no comando acima corresponde ao último parâmetro do último
# comando, útil ao baixar e logo tornar executável
Para inserir todos os argumentos do último comando
!*
Para alternar entre o começo da linha e a posição atual
Ctrl-x Ctrl-x
Para exibir a vesão do bash
Ctrl-x Ctrl-v
Para fazer uma busca incremental reversa no histórico de comandos
Ctrl-r ......... comece a digitar um comando longo recém executado
Para "ver" como foi a execução do ultimo comando ping
!ping:p
Substituindo um trecho do comando anterior "use o circunflexo mesmo"
ping -c 2 www.google.com
^google^yahoo
Tabém pode ser assim:
!!:gs/foo/bar
E tem mais...
Bash Shell Shortcuts Bash, which is the default shell in Linux contains a whole lot of key bindings which makes it really easy to use . The most commonly used shortcuts are listed below : ____________CTRL Key Bound_____________ Ctrl + a - Jump to the start of the line Ctrl + b - Move back a char Ctrl + c - Terminate the command Ctrl + d - Delete from under the cursor Ctrl + e - Jump to the end of the line Ctrl + f - Move forward a char Ctrl + k - Delete to EOL Ctrl + l - Clear the screen Ctrl + r - Search the history backwards Ctrl + R - Search the history backwards with multi occurrence Ctrl + u - Delete backward from cursor Ctrl + xx - Move between EOL and current cursor position Ctrl + x @ - Show possible hostname completions Ctrl + z - Suspend/ Stop the command ____________ALT Key Bound___________ Alt + < - Move to the first line in the history Alt + > - Move to the last line in the history Alt + ? - Show current completion list Alt + * - Insert all possible completions Alt + / - Attempt to complete filename Alt + . - Yank last argument to previous command Alt + b - Move backward Alt + c - Capitalize the word Alt + d - Delete word Alt + f - Move forward Alt + l - Make word lowercase Alt + n - Search the history forwards non-incremental Alt + p - Search the history backwards non-incremental Alt + r - Recall command Alt + t - Move words around Alt + u - Make word uppercase Alt + back-space - Delete backward from cursor ----------------More Special Keybindings------------------- Here "2T" means Press TAB twice $ 2T - All available commands(common) $ (string)2T - All available commands starting with (string) $ /2T - Entire directory structure including Hidden one $ 2T - Only Sub Dirs inside including Hidden one $ *2T - Only Sub Dirs inside without Hidden one $ ~2T - All Present Users on system from "/etc/passwd" $ $2T - All Sys variables $ @2T - Entries from "/etc/hosts" $ =2T - Output like ls or dir
Abrindo o ultimo comando no vim
fc
Veja também:
- 10 bons hábitos para programadores shell (em inglês)
- http://www.tuxarena.com/2010/12/10-bash-tips-for-working-faster-with-the-shell-part-1-of-2/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ------------------------------------------------------ | |
# FILE: ~/.inputrc | |
# CREATED: Qui 13/Out/2011 hs 09:39 | |
# LAST CHANGE: Qui 13/Out/2011 hs 09:39 | |
# SITE: http://vivaotux.blogspot.com | |
# TWITTER: http://www.twitter.com/voyeg3r | |
# EMAIL: <voyeg3r gmail.com> | |
# DOWNLOAD: https://gist.github.com/1284081 | |
# | |
# key bindings for bash | |
# | |
# ( O O ) | |
# --------------oOO--(_)--OOo--------------------------- | |
#------------------------------------------------------- | |
# Use `bind -v` to see current settings | |
#------------------------------------------------------- | |
# definir no ~/ .bashrc o local do inputrc | |
# INPUTRC=~/.inputrc | |
# para baixar: | |
# wget -c https://raw.github.com/gist/1284081 -O ~/.inputrc | |
# alternative download | |
# wget -c http://pastie.org/pastes/2689512/text -C ~/.inpurtc | |
# Referências | |
# https://bugs.launchpad.net/ubuntu/+source/base-files/+bug/103986 | |
# http://superuser.com/questions/222390/making-bash-tab-completion-more-like-cmd-exe | |
# pesquisar sobre as opções 'shopt' do bash | |
# pesquisar as opções 'cmdhist' 'nocaseglob' 'nocasematch' | |
# By default, C-x C-r is bound to re-read-init-file. | |
# Adding this to your /etc/inputrc or ~/.inputrc will result in a character | |
# # being appended to any file-names returned by completion, in much the same | |
# # way as ls -F works. | |
set visible-stats on | |
set blink-matching-paren on | |
set bell-style visible | |
set convert-meta off | |
set input-meta on | |
set output-meta on | |
$if Bash | |
# Search history back and forward using page-up and page-down | |
"\e[5~": history-search-backward | |
"\e[6~": history-search-forward | |
# Cycle through ambiguous completions instead of list (option bellow) | |
"\C-i": menu-complete | |
# Completion | |
set match-hidden-files off | |
set completion-query-items 350 | |
set completion-ignore-case on | |
set show-all-if-ambiguous on | |
set show-all-if-unmodified on | |
# do history expansion when space entered | |
Space: magic-space | |
$endif | |
$include /etc/inputrc | |
# put in your ~/.bashrc | |
# complete -d cd mkdir rmdir | |
# exec bash (to reload bash) |