Você está na página 1de 9

Comandos Linux

Salviano A. Leo
21/12/2013

Sumrio
1 ls - listagem detalhada com ordenao por tipo de arquivo

2 Uso das teclas "Page Up"e "Page Down"para navegar pelo histrico de comandos
3
3 Como apagar arquivos expandidos no local errado com o comando tar

4 20 Unix Command Line Tricks


4.1 Deleting a HUGE file . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.2 Want to cache console output? . . . . . . . . . . . . . . . . . . . . . .
4.3 Restoring deleted /tmp folder . . . . . . . . . . . . . . . . . . . . . .
4.4 Locking a directory . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.5 Password protecting file in vim text editor . . . . . . . . . . . . . . .
4.6 Clear gibberish all over the screen . . . . . . . . . . . . . . . . . . . .
4.7 Show information about known users in the Linux based system . . .
4.8 How do I fix mess created by accidentally untarred files in the current
4.9 Confused on a top command output? . . . . . . . . . . . . . . . . . .
4.10 Want to run the same command again? . . . . . . . . . . . . . . . . .
4.11 Get a reminder you when you have to leave . . . . . . . . . . . . . . .
4.12 Home sweet home . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.13 Editing a file being viewed with less pager . . . . . . . . . . . . . . .
4.14 List all files or directories on your system . . . . . . . . . . . . . . . .
4.15 Build directory trees in a single command . . . . . . . . . . . . . . .
4.16 Copy file into multiple directories . . . . . . . . . . . . . . . . . . . .
4.17 Quickly find differences between two directories . . . . . . . . . . . .
4.18 Text formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.19 See the output and write it to a file . . . . . . . . . . . . . . . . . . .

3
3
4
4
4
5
5
5
6
6
6
7
7
8
8
8
8
9
9
9

. . .
. . .
. . .
. . .
. . .
. . .
. . .
dir?
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

ls - listagem detalhada com ordenao por tipo de arquivo

O comando ls possui uma grande quantidade de opes, tantas que at se diz que ele foge
completamente filosofia do Unix, em que cada programa desempenha apenas uma funo. O
comando ls um mundo por si s. J que assim, no custa conhecer um pouco mais de seus
recursos.
1

O comando ls -lhXG ir listar os arquivos omitindo a informao do grupo e orden-los


segundo o tipo de arquivo.
As diretivas usadas significam:
Diretiva Formato longo
-l
-h
human-readable
-X
-G
no-group

Significado
listagem longa
formato legvel por humanos
ordenar alfabeticamente
no exibir informaes sobre propriedade de grupo

Para entender melhor, vejam o que acontece em um diretrio


> ls - lhXG
-rw - rw -r - -rw - rw -r - -rw - rw -r - - rwxrwxr - x
-rw -r - -r - -rw - - - - - - -rw - rw -r - -rw - rw -r - -rw -r - -r - -rw - rw -r - -rw - rw -r - -rw - rw -r - -rw -r - -r - -rw - rw -r - -rw - rw -r - -rw - rw -r - -rw - rw -r - -rw - rw -r - -

1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1

salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano

5.9 K
6.2 K
2.7 K
732 K
46 K
112 K
164 K
164 K
392 K
3.6 M
25 K
1.1 K
1020
17 K
180
193
406 K
543 K

Abr
Mar
Out
Jan
Jul
Jan
Fev
Fev
Fev
Jan
Jan
Out
Jan
Jan
Out
Out
Jan
Jan

30
28
8
19
13
23
6
3
5
20
19
3
16
19
4
4
19
19

2013
2012
12:37
17:47
2012
2014
17:50
08:50
18:26
17:24
17:58
16:31
18:06
17:54
2012
2012
17:08
17:10

cpu_Graphing_Script_0
lista
lixo1
nlsl
mix165 . dat
INFOR495 . doc
NLSL . MOMD - SAL . tar . gz
NLSL . MOMD . tar . gz
Test - input . tar . gz
build . log
mix165Au . log
plotfile_demo . py
mix165au . run
mix165 . spc
equipe_sort . txt
equipe . txt
NLSL . MOMD . zip
PC . NEW . zip

Agora somente com as opes textttls -lh, temos


> 'ls ' - lh
-rw - rw -r - -rw - rw -r - -rw - rw -r - -rw - rw -r - -rw - - - - - - -rw - rw -r - -rw - rw -r - -rw - rw -r - -rw -r - -r - -rw -r - -r - -rw - rw -r - - rwxrwxr - x
-rw - rw -r - -rw - rw -r - -rw - rw -r - -rw - rw -r - -rw - rw -r - -rw -r - -r - -

1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1

salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano

salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano
salviano

3.6 M
5.9 K
180
193
112 K
6.2 K
2.7 K
25 K
1020
46 K
17 K
732 K
164 K
164 K
406 K
543 K
1.1 K
392 K

Jan
Abr
Out
Out
Jan
Mar
Out
Jan
Jan
Jul
Jan
Jan
Fev
Fev
Jan
Jan
Out
Fev

20
30
4
4
23
28
8
19
16
13
19
19
6
3
19
19
3
5

17:24
2013
2012
2012
2014
2012
12:37
17:58
18:06
2012
17:54
17:47
17:50
08:50
17:08
17:10
16:31
18:26

build . log
cpu_Graphing_Script_0
equipe_sort . txt
equipe . txt
INFOR495 . doc
lista
lixo1
mix165Au . log
mix165au . run
mix165 . dat
mix165 . spc
nlsl
NLSL . MOMD - SAL . tar . gz
NLSL . MOMD . tar . gz
NLSL . MOMD . zip
PC . NEW . zip
plotfile_demo . py
Test - input . tar . gz

Uso das teclas "Page Up"e "Page Down"para navegar


pelo histrico de comandos

Acrescentando duas linhas ao arquivo .inputrc podemos fazer com que as teclas <Page Up>
e <Page Down> sejam usadas para navegar atravs do histrico de comandos do bash.
Em meu sistema LinuxMint 17.1 o arquivo .inputrc no existia, ento o arquivo foi criado
com o seguinte contedo:
"\e[5~": history-search-backward
"\e[6~": history-search-forward
Isto feito, ao abrir uma nova tela as teclas <Page Up> e <Page Down> j estavam funcionando
para navegar pelo histrico de comandos. Caso voc digite o comeo do comando pelo qual
est procurando, a navegao ir exibir comandos que comecem com o texto digitado. Caso
contrrio, a navegao se dar pelo histrico completo de comandos.

Como apagar arquivos expandidos no local errado com


o comando tar

Geralmente esperamos que um arquivo tar possua um diretrio principal que abrigue todos
os demais arquivos. Infelizmente nem sempre assim e s vezes abrimos um arquivo tar em
um diretrio e misturamos o contedo dos dois diretrios. Para remover os arquivos criados
erroneamente sempre demorado e propenso a erros.
Mas existe um jeito simples, rpido e seguro de se fazer isto.
rm - rf ` tar ztf arquivo . tar . gz `

ou ainda
rm - rf $ ( tar ztf arquivo . tar . gz )

Se voc quer realmente garantir que nada ser apagado indevidamente, acrescente a diretiva
"-i", para realizar a remoo dos arquivos e diretrios de forma interativa.
rm - rfi $ ( tar ztf arquivo . tar . gz )

20 Unix Command Line Tricks

Let us start new year with these Unix command line tricks to increase productivity at the
Terminal. I have found them over the years and Im 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 a
HUGE file, enter:

> / path / to / file . log


# or use the following syntax
: > / path / to / file . log
# finally delete it
rm / path / to / file . log

4.2

Want to cache console output?

Try the script command line utility to create a typescript of everything printed on your terminal.
script my . terminal . session

Type commands:
ls
date
sudo service foo stop

To exit (to end script session) type exit or logout or press control-D
exit

To view type:
more my . terminal . session
less my . terminal . session
cat my . terminal . session

4.3

Restoring deleted /tmp folder

As my journey continues with Linux and Unix shell, I made a few mistakes. I accidentally
deleted /tmp folder. To restore it all you have to do is:
mkdir / tmp
chmod 1777 / tmp
chown root : root / tmp
ls - ld / tmp

4.4

Locking a directory

For privacy of my data I wanted to lock down /downloads on my file server. So I ran:
chmod 0000 / downloads

The root user can still has access and ls and cd commands will not work. To go back:
chmod 0755 / downloads

4.5

Password protecting file in vim text editor

Afraid that root user or someone may snoop into your personal text files? Try password
protection to a file in vim, type:
vim + X filename

Or, before quitting in vim use :X vim command to encrypt your file and vim will prompt
for a password.

4.6

Clear gibberish all over the screen

Just type:
reset

Becoming human
Pass 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:
ls - lh
# print sizes in human readable format ( e . g . , 1 K 234 M 2 G )
df -h
df -k
# show output in bytes , KB , MB , or GB
free -b
free -k
free -m
free -g
# print sizes in human readable format ( e . g . , 1 K 234 M 2 G )
du -h
# get file system perms in human readable format
stat -c % A / boot
# compare human readable numbers
sort -h -a file
# display the CPU information in human readable format on a Linux
lscpu
lscpu -e
lscpu -e = cpu , node
# Show the size of each file but in a more human readable way
tree -h
tree -h / boot

4.7

Show information about known users in the Linux based system

Just type:
# # linux version ##
lslogins
# # BSD version ##
logins

Sample outputs:
UID
0
1
2
3
4
5
6
7
8
10
11
12
13
14
27
38
48
68
69
72
74
81
89
99
173
497
498
499

USER
PWD - LOCK PWD - DENY LAST - LOGIN
root
0
0
22:37:59
bin
0
1
daemon
0
1
adm
0
1
lp
0
1
sync
0
1
shutdown
0
1 2014 - Dec17
halt
0
1
mail
0
1
uucp
0
1
operator
0
1
games
0
1
gopher
0
1
ftp
0
1
mysql
0
1
ntp
0
1
apache
0
1
haldaemon
0
1
vcsa
0
1
tcpdump
0
1
sshd
0
1
dbus
0
1
postfix
0
1
nobody
0
1
abrt
0
1
vnstat
0
1
nginx
0
1
saslauth
0
1

4.8

GECOS
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
uucp
operator
games
gopher
FTP User
MySQL Server
Apache
HAL daemon
virtual console memory owner
Privilege - separated SSH
System message bus
Nobody
vnStat user
nginx user
" Saslauthd user "

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 / var / www / html /
/ bin / rm -f " $ ( tar ztf / path / to / file . tar . gz ) "

4.9

Confused on a top command output?

Seriously, you need to try out htop instead of top:


sudo htop

4.10

Want to run the same command again?

Just type !!. For example:

/ myhome / dir / script / name arg1 arg2


# To run the same command again
!!
# # To run the last command again as root user
sudo !!

The !! repeats the most recent command. To run the most recent command beginning with
"foo":
! foo
# Run the most recent command beginning with " service " as root
sudo ! service

The !$ use to run command with the last argument of the most recent command:
# Edit nginx . conf
sudo vi / etc / nginx / nginx . conf
# Test nginx . conf for errors
/ sbin / nginx -t -c / etc / nginx / nginx . conf
# After testing a file with "/ sbin / nginx -t -c / etc / nginx / nginx . conf " , you
# can edit file again with vi
sudo 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:
leave + hhmm

Where,
hhmm The time of day is in the form hhmm where hh is a time in hours (on a 12 or 24 hour
clock), and mm are minutes. All times are converted to a 12 hour clock, and assumed to
be 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:

export CDPATH =/ var / www :/ nas10

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:
less *. c
less foo . html
# # Press v to edit file ##
# # Quit from editor and you would return to the less pager again ##

4.14

List all files or directories on your system

To see all of the directories on your system, run:


find / - type d | less

# List all directories in your $HOME


find $HOME - type d - ls | less
To see all of the files , run :
find / - type f | less
# List all files in your $HOME
find $HOME - 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:
mkdir -p / jail /{ dev , bin , sbin , etc , usr , lib , lib64 }
ls -l / jail /

4.16

Copy file into multiple directories

Instead of running:
cp / path / to / file / usr / dir1
cp / path / to / file / var / dir2
cp / path / to / file / nas / dir3

Run the following command to copy file into multiple dirs:


echo / usr / dir1 / var / dir2 / nas / dir3 |

xargs -n 1 cp -v / path / to / file

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:
ls -l / tmp / r
ls -l / tmp / s
# Compare two folders using diff ##
diff / tmp / r / / tmp / 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, Im going to reformat
file by wrapping overlong lines and filling short lines:
fmt file . txt

You can also split long lines, but do not refill i.e. wrap overlong lines, but do not fill short
lines:
fmt -s file . txt

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 named
my.log:
mycoolapp arg1 arg2 input . file | tee my . log

The tee command ensures that you will see mycoolapp output on on the screen and to a
file same time.