Download - Shell Dicas
-
8/8/2019 Shell Dicas
1/9
Comandos Linux
Salviano A. Leão
21/12/2013
Sumário
1 ls - listagem detalhada com ordenação por tipo de arquivo 1
2 Uso das teclas "Page Up"e "Page Down"para navegar pelo histórico de co-mandos 3
3 Como apagar arquivos expandidos no local errado com o comando tar 3
4 20 Unix Command Line Tricks 3
4.1 Deleting a HUGE file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34.2 Want to cache console output? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44.3 Restoring deleted /tmp folder . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44.4 Locking a directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44.5 Password protecting file in vim text editor . . . . . . . . . . . . . . . . . . . . . 5
4.6 Clear gibberish all over the screen . . . . . . . . . . . . . . . . . . . . . . . . . . 54.7 Show information about known users in the Linux based system . . . . . . . . . 54.8 How do I fix mess created by accidentally untarred files in the current dir? . . . 64.9 Confused on a top command output? . . . . . . . . . . . . . . . . . . . . . . . . 64.10 Want to run the same command again? . . . . . . . . . . . . . . . . . . . . . . . 64.11 Get a reminder you when you have to leave . . . . . . . . . . . . . . . . . . . . . 74.12 Home sweet home . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74.13 Editing a file being viewed with less pager . . . . . . . . . . . . . . . . . . . . . 84.14 List all files or directories on your system . . . . . . . . . . . . . . . . . . . . . . 84.15 Build directory trees in a single command . . . . . . . . . . . . . . . . . . . . . 8
4.16 Copy file into multiple directories . . . . . . . . . . . . . . . . . . . . . . . . . . 84.17 Quickly find differences between two directories . . . . . . . . . . . . . . . . . . 94.18 Text formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94.19 See the output and write it to a file . . . . . . . . . . . . . . . . . . . . . . . . . 9
1 ls - listagem detalhada com ordenação por tipo de ar-
quivo
O comando ls possui uma grande quantidade de opções, tantas que até se diz que ele foge
completamente à filosofia do Unix, em que cada programa desempenha apenas uma função. Ocomando ls é um mundo por si só. Já que é assim, não custa conhecer um pouco mais de seusrecursos.
1
-
8/8/2019 Shell Dicas
2/9
O comando ls -lhXG irá listar os arquivos omitindo a informação do grupo e ordená-lossegundo o tipo de arquivo.
As diretivas usadas significam:
Diretiva Formato longo Significado
-l listagem longa-h –human-readable formato legível por humanos-X ordenar alfabeticamente-G –no-group não exibir informações sobre propriedade de grupo
Para entender melhor, vejam o que acontece em um diretório
> ls - lhX G
- rw - rw - r -- 1 s al vi an o 5 . 9 K A br 3 0 2 01 3 c p u _G r ap hi n g_ Sc r ip t_ 0
- rw - rw - r- - 1 s al vi an o 6 .2 K M ar 28 2 01 2 l is ta
- rw - rw - r- - 1 s al vi an o 2 .7 K O ut 8 1 2 :3 7 l ix o1
- rw xr wx r - x 1 s al vi an o 7 32 K J an 1 9 1 7: 47 n ls l- rw - r- -r - - 1 s al vi an o 46 K Jul 1 3 2 01 2 mi x1 65 . da t
- rw - - -- - -- 1 s a lv ia no 1 1 2 K Ja n 23 2 01 4 I N FO R4 95 . d oc
- rw - rw - r -- 1 s al vi an o 1 6 4 K F ev 6 1 7: 50 N LS L . MO MD - S A L. t ar . gz
- rw - rw - r -- 1 s a l vi an o 1 64 K F ev 3 0 8 :5 0 N LS L . MO MD . t ar . gz
- rw - r -- r -- 1 s a l vi an o 3 92 K F ev 5 1 8 :2 6 T es t - i np ut . t ar . gz
- rw - rw - r -- 1 s al vi an o 3 .6 M J an 2 0 1 7 :2 4 b ui ld . l og
- rw - rw - r -- 1 s a lv ia no 2 5K J an 1 9 1 7 :5 8 m i x1 65 Au . l og
- rw - rw - r -- 1 s a l vi an o 1 .1 K O ut 3 1 6 :3 1 p l ot fi le _d em o . py
- rw - r -- r -- 1 s al vi an o 1 02 0 J an 1 6 1 8: 06 m ix 16 5a u . ru n
- rw - rw - r- - 1 s al vi an o 17 K J an 19 1 7: 54 m ix 16 5. sp c
- rw - rw - r- - 1 sa lv ia no 1 80 Out 4 2 01 2 e qu ip e_ so rt . tx t
-rw - rw -r -- 1 sa lvi ano 193 Out 4 2012 eq ui pe . txt
- rw - rw - r -- 1 s al vi an o 4 06 K J an 1 9 1 7: 08 N LS L . MO MD . z ip- rw - rw - r -- 1 s al vi an o 5 43 K J an 1 9 1 7 :1 0 P C. N EW . z ip
Agora somente com as opções “textttls -lh”, temos
> 'ls ' - lh
- rw - rw - r -- 1 s al vi an o s al vi an o 3 .6 M J an 2 0 1 7: 24 b ui ld . l og
- rw - rw - r -- 1 s al vi an o s al vi an o 5 .9 K A br 3 0 2 01 3 c pu _G r ap hi n g_ Sc r ip t_ 0
- rw - rw - r- - 1 s al vi an o sa lv ia no 18 0 Out 4 2 01 2 eq ui pe _s or t . tx t
- rw - rw - r- - 1 sa lv ia no s al vi an o 19 3 O ut 4 2 01 2 e qu ip e .tx t
- rw - - -- - -- 1 s al vi an o s a l vi an o 1 12 K J a n 2 3 2 01 4 I N FO R4 95 . d oc
- rw - rw - r- - 1 s al vi an o s al vi an o 6 .2 K M ar 28 2 01 2 l is ta- rw - rw - r- - 1 s al vi an o s al vi an o 2 .7 K O ut 8 1 2: 37 l ix o1
- rw - rw - r -- 1 s al vi an o s a l vi an o 2 5K J a n 1 9 1 7: 58 m ix 16 5A u . lo g
- rw - r -- r -- 1 s al vi an o s al vi an o 1 02 0 J an 1 6 1 8: 06 m ix 16 5a u . ru n
- rw - r- -r - - 1 s a lv ia no s al vi an o 46 K J ul 1 3 2 01 2 m ix 16 5 .da t
- rw - rw - r -- 1 s a l vi an o s a lv ia no 1 7K J an 1 9 1 7 :5 4 m i x1 65 . s pc
- rw xr wx r - x 1 s al vi an o s al vi an o 7 32 K J an 1 9 1 7: 47 n ls l
- rw - rw - r -- 1 s al vi an o s al vi an o 1 6 4 K F ev 6 1 7: 50 N LS L . MO MD - S A L. t ar . gz
- rw - rw - r -- 1 s al vi an o s al vi an o 1 6 4 K F ev 3 0 8 :5 0 N L SL . M OM D . ta r .g z
- rw - rw - r -- 1 s al vi an o s al vi an o 4 06 K J an 1 9 1 7: 08 N LS L . MO MD . z ip
- rw - rw - r -- 1 s al vi an o s al vi an o 5 43 K J an 1 9 1 7: 10 P C. N EW . zi p
- rw - rw - r -- 1 s al vi an o s al vi an o 1 . 1 K O ut 3 1 6 :3 1 p l o tf il e_ de mo . p y
- rw - r -- r -- 1 s al vi an o s al vi an o 3 9 2 K F ev 5 1 8: 26 T es t - i np ut . t ar . gz
2
-
8/8/2019 Shell Dicas
3/9
2 Uso das teclas "Page Up"e "Page Down"para navegar
pelo histórico de comandos
Acrescentando duas linhas ao arquivo .inputrc podemos fazer com que as teclas e sejam usadas para navegar através do histórico de comandos do bash.
Em meu sistema LinuxMint 17.1 o arquivo .inputrc não existia, então o arquivo foi criadocom o seguinte conteúdo:
"\e[5~": history-search-backward
"\e[6~": history-search-forward
Isto feito, ao abrir uma nova tela as teclas e já estavam funcionandopara navegar pelo histórico de comandos. Caso você digite o começo do comando pelo qualestá procurando, a navegação irá exibir comandos que comecem com o texto digitado. Casocontrário, a navegação se dará pelo histórico completo de comandos.
3 Como apagar arquivos expandidos no local errado com
o comando tar
Geralmente esperamos que um arquivo tar possua um diretório principal que abrigue todosos demais arquivos. Infelizmente nem sempre é assim e às vezes abrimos um arquivo tar emum diretório e misturamos o conteúdo dos dois diretórios. Para remover os arquivos criadoserroneamente é sempre demorado e propenso a erros.
Mas existe um jeito simples, rápido e seguro de se fazer isto.
r m - rf t a r z t f a r q ui v o . t a r . gz
ou ainda
r m - rf $ ( t ar z tf a r qu i vo . t a r . gz )
Se você quer realmente garantir que nada será apagado indevidamente, acrescente a diretiva"-i", para realizar a remoção dos arquivos e diretórios de forma interativa.
r m - r fi $ ( t ar z tf a r qu i vo . t a r . gz )
4 20 Unix Command Line Tricks
Let us start new year with these Unix command line tricks to increase productivity at theTerminal. I have found them over the years and I’m now going to share with you.
4.1 Deleting a HUGE file
I had a huge log file 200GB I need to delete on a production web server. My rm and ls command
was crashed and I was afraid that the system to a crawl with huge disk I/O load. To remove aHUGE file, enter:
3
-
8/8/2019 Shell Dicas
4/9
> / p a t h / t o / f il e . l o g
# o r u se t he f ol lo wi ng s yn ta x
: > / p a th / t o / fi le . l o g
# f in al ly d el et e i t
r m / p a t h / t o / f il e . l o g
4.2 Want to cache console output?
Try the script command line utility to create a typescript of everything printed on your terminal.
s c r ip t m y . t e r m in a l . s e s s i on
Type commands:
lsdate
s ud o s e rv i ce f oo s to p
To exit (to end script session) type exit or logout or press control-D
exit
To view type:
more my . t e rm i na l . s es si on
l e ss m y . t e r m in a l . s e s s i oncat m y . t e r m i n a l . s e s s i o n
4.3 Restoring deleted /tmp folder
As my journey continues with Linux and Unix shell, I made a few mistakes. I accidentallydeleted /tmp folder. To restore it all you have to do is:
mkdi r / tm p
c hm o d 1 77 7 / t mp
c h ow n r o ot : r o o t / t m pl s - ld / t mp
4.4 Locking a directory
For privacy of my data I wanted to lock down /downloads on my file server. So I ran:
c h mo d 0 0 00 / d o w n l o ad s
The root user can still has access and ls and cd commands will not work. To go back:
c h mo d 0 7 55 / d o w n l o ad s
4
-
8/8/2019 Shell Dicas
5/9
4.5 Password protecting file in vim text editor
Afraid that root user or someone may snoop into your personal text files? Try passwordprotection to a file in vim, type:
v im + X f i le n am e
Or, before quitting in vim use :X vim command to encrypt your file and vim will promptfor a password.
4.6 Clear gibberish all over the screen
Just type:
reset
Becoming humanPass the -h or -H (and other options) command line option to GNU or BSD utilities to get
output of command commands like ls, df, du, in human-understandable formats:
l s - lh
# p ri nt s iz es i n h um an r ea da bl e f or ma t ( e .g . , 1 K 2 34 M 2 G )
df - h
df - k
# s ho w o ut pu t in byt es , KB , MB , or GB
f re e - b
f re e - k
f re e - mf re e - g
# p ri nt s iz es i n h um an r ea da bl e f or ma t ( e .g . , 1 K 2 34 M 2 G )
du - h
# g et f il e s ys te m p er ms i n h um an r ea da bl e f or ma t
s ta t - c % A / b oo t
# c o mp a re h um a n r e ad a bl e n u mb e rs
s or t - h - a f il e
# d is pl ay t he C PU i nf or ma ti on in h um an r ea da bl e f or ma t o n a L in ux
lscpu
l sc p u - e
l s cp u - e = cp u , n o d e
# S ho w th e s iz e o f e ac h f il e b ut in a mo re h um an r ea da bl e wa yt re e - h
t re e - h / b oo t
4.7 Show information about known users in the Linux based system
Just type:
# # l in ux v er si on # #
l s l o g i n s
# # B SD v er si on # #
logins
5
-
8/8/2019 Shell Dicas
6/9
Sample outputs:
UID USER PWD - LOCK PWD - DENY LAST - L OGI N GEC OS
0 root 0 0 2 2 :3 7 :5 9 root
1 bin 0 1 bin
2 da em on 0 1 da em on3 adm 0 1 adm
4 lp 0 1 lp
5 sync 0 1 sync
6 s h ut d ow n 0 1 2014 - Dec1 7 s h ut d ow n
7 halt 0 1 halt
8 mail 0 1 mail
10 uucp 0 1 uucp
11 o p er a to r 0 1 o p er a to r
12 game s 0 1 gam es
13 go ph er 0 1 g oph er
14 ftp 0 1 FTP User
27 mysq l 0 1 MyS QL S er ver
38 ntp 0 1
48 ap ac he 0 1 A pac he
68 h a l da e m on 0 1 HAL d ae mon
69 vcsa 0 1 v ir tu a l co ns ol e me mor y o wner
72 t cp du mp 0 1
74 sshd 0 1 Privile ge - s ep a r at e d SSH
81 dbus 0 1 S yst em m es sa ge bus
89 p os tf ix 0 1
99 no bo dy 0 1 N obo dy
173 abrt 0 1
497 vn st at 0 1 vn St at user
498 ngin x 0 1 ngi nx user
499 s a sl a ut h 0 1 " S as l a u th d user "
4.8 How do I fix mess created by accidentally untarred files in the
current dir?
So I accidentally untar a tarball in /var/www/html/ directory instead of /home/projects/www/-current. It created mess in /var/www/html/. The easiest way to fix this mess:
cd / v a r / w w w / h t m l /
/ b in / r m - f " $ ( ta r z tf / p a th / t o / fi le . t a r . gz ) "
4.9 Confused on a top command output?
Seriously, you need to try out htop instead of top:
s u do h t op
4.10 Want to run the same command again?
Just type !!. For example:
6
-
8/8/2019 Shell Dicas
7/9
/ m y h o me / d i r / s c r i p t / n a me a r g1 a r g2
# T o r un t he s am e c om ma nd a ga in
!!
# # T o r un t he l as t c om ma nd a ga in a s r oo t u se rs ud o ! !
The !! repeats the most recent command. To run the most recent command beginning with"foo":
! f o o
# R un t he m os t r ec en t c om ma nd b eg in ni ng w it h " s er vi ce " a s r oo t
s u do ! s e r v i ce
The !$ use to run command with the last argument of the most recent command:
# E di t n g in x . c on f
s u do v i / e t c / n g i nx / n g i n x . c o n f
# T es t n g in x . c on f f or e r ro r s
/ s b i n / n g i nx - t - c / e t c / n g i nx / n g i n x . c o n f
# A ft e r t e st i ng a f il e w it h " / s bi n / n gi nx - t - c / e tc / n g in x / n gi n x . co nf " , y ou
# c an e di t f il e a ga in w it h v i
s ud o vi ! $
4.11 Get a reminder you when you have to leave
If you need a reminder to leave your terminal, type the following command:
l e av e + h h m m
Where,
hhmm The time of day is in the form hhmm where hh is a time in hours (on a 12 or 24 hourclock), and mm are minutes. All times are converted to a 12 hour clock, and assumed tobe in the next 12 hours.
4.12 Home sweet home
Want to go the directory you were just in? Run:
cd -
Need to quickly return to your home directory? Enter:
cd
The variable CDPATH defines the search path for the directory containing directories:
7
-
8/8/2019 Shell Dicas
8/9
export C D P A T H = / v a r / w w w : / n a s 1 0
Now, instead of typing cd /var/www/html/ I can simply type the following to cd into/var/www/html path:
cd html
4.13 Editing a file being viewed with less pager
To edit a file being viewed with less pager, press v. You will have the file for edit under $EDITOR:
l es s * . c
l e ss f o o . h tm l
# # P re ss v to e di t f il e ##
# # Q ui t f ro m e di to r a nd y ou w ou ld r et ur n to t he l es s p ag er a ga in # #
4.14 List all files or directories on your system
To see all of the directories on your system, run:
find / - type d | less
# L is t a ll d ir ec to ri es i n y ou r $ HO ME
f in d $ HO ME - type d - ls | less
To se e al l of th e f ile s , r un :
find / - type f | less
# L is t a ll f il es i n y ou r $ HO ME
f in d $ HO ME - type f - ls | less
4.15 Build directory trees in a single command
You can create directory trees one at a time using mkdir command by passing the -p option:
mkdi r -p / jail /{ de v , bi n , sb in , et c , us r , li b , lib6 4 }
l s - l / j a il /
4.16 Copy file into multiple directories
Instead of running:
c p / p a t h / t o / f il e / u s r / d i r1c p / p a t h / t o / f il e / v a r / d i r2
c p / p a t h / t o / f il e / n a s / d i r3
8
-
8/8/2019 Shell Dicas
9/9
Run the following command to copy file into multiple dirs:
echo / us r / di r1 / v ar / d ir 2 / n as / d ir 3 | x ar gs - n 1 c p - v / p at h /t o/ f il e
Creating a shell function is left as an exercise for the reader
4.17 Quickly find differences between two directories
The diff command compare files line by line. It can also compare two directories:
l s - l / t m p /r
l s - l / t m p /s
# C om pa re t wo f ol de rs u si ng d if f # #
d if f / t mp / r / / t mp / s /
Fig. : Finding differences between folders
Fig. : Finding differences between folders
4.18 Text formatting
You can reformat each paragraph with fmt command. In this example, I’m going to reformatfile by wrapping overlong lines and filling short lines:
f m t f i le . t x t
You can also split long lines, but do not refill i.e. wrap overlong lines, but do not fill short
lines:
f mt - s f il e . t xt
4.19 See the output and write it to a file
Use the tee command as follows to see the output on screen and also write to a log file namedmy.log:
m y co o l ap p arg1 ar g2 i nput . file | te e my . lo g
The tee command ensures that you will see mycoolapp output on on the screen and to afile same time.
9