Arquivo mensal 18 de abril de 2017


Bash Command Line Examples.

After having spent years on unix systems, shell scripting still continues to elude me. Hence these reminders.

  1. For Loops over lists
  2. While loop
  3. The Absolute Current Working Directory
  4. Getting a line count on various directories

For Loops over lists

  • To add a bunch of files to subversion
for f in Button.phi Buttons.phi Cells.phi ; do svn add $f; done
for f in `ls -l *.phi`; do svn add $f; done
  • A more complete sample
ls *.xml
file1.xml  file2.xml  file3.xml

ls *.xml > list

for i in `cat list`; do cp "$i" "$i".bak ; done

ls *.xml*
file1.xml  file1.xml.bak  file2.xml  file2.xml.bak  file3.xml  file3.xml.bak
  • To clear emails to us**@ex*****.com out of my mail queue after inspecting the affected files
cd /path/to/mailqueue
ls -l `grep -l 'us**@ex*****.com' \`find . -type f\``
rm -f `grep -l 'us**@ex*****.com' \`find . -type f\``

Note: Be sure to run the ls before the rm.

  • A little awking. PIDs of all processes using alsa. Grabs the 2nd column out of a listing.
lsof | grep alsa | awk '{print $2}'
  • This alias produces a sorted list of services and the ports they’re listening on.
alias ports='sudo /usr/bin/lsof -nPi | grep LIST | awk '\''{printf "%-20s%-5s%-5s%s\n",$1,$5,$7,$8}'\'' | sort | uniq'
  • Running ports would then produce something like this:
cupsd               IPv4 TCP
master              IPv4 TCP
mysqld              IPv4 TCP
portmap             IPv4 TCP  *:111
rpc.mount           IPv4 TCP  *:657
rpc.statd           IPv4 TCP  *:894
smbd                IPv4 TCP  *:139
smbd                IPv4 TCP  *:445
sshd                IPv6 TCP  *:22

While loop

  • Keeping my mail inbox from overflowing while running email stress tests
cd /path/to/maildir/new
while true; do rm -f *; sleep 5; done

The Absolute Current Working Directory

  • AKA Getting the realpath of a location.
  • This is really more useful in scripts, but here goes:
MYCWD=`dirname \`readlink -e $0\``

Getting a line count on various directories

T=0; \
for f in dir1 dir3 dir10; do \
  N=0; \
 for n in `find $f -type f -exec wc -l {} \; | awk '{print $1}'`; do\
    N=$(‎( $M + $n )); \
  done; \
  T=$(‎( $T + $N)); \
  echo $N - $f; \
done; \
echo $T - Total

4686 - dir1
4894 - dir3
981037 - dir10
990617 - Total

Visualizando o conteúdo das mensagens fila postfix.

Para visualizar o conteúdo de uma mensagem, utilizamos o comando “postcat” como neste exemplo:

postcat -vq MESSAGEID

O exemplo da mensagem acima, seria:

postcat -vq 96C9D1D1620

A saída do comando acima seria similar a esta:

ro**@lo*******.localdomain:~# postcat -vq D576011ED32
postcat: name_mask: all
postcat: inet_addr_local: configured 2 IPv4 addresses
postcat: inet_addr_local: configured 2 IPv6 addresses
*** ENVELOPE RECORDS deferred/D/D576011ED32 ***
message_size: 705 713 1 0 705
message_arrival_time: Tue Nov 24 19:30:25 2015
create_time: Tue Nov 24 19:30:25 2015
named_attribute: log_ident=D576011ED32