You are here: Home Cheat Sheets Bash Command Line Examples

Bash Command Line Examples

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

 

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 user@example.com out of my mail queue after inspecting the affected files
cd /path/to/mailqueue
ls -l `grep -l 'user@example.com' \`find . -type f\``
rm -f `grep -l 'user@example.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  127.0.0.1:631
master IPv4 TCP 127.0.0.1:25
mysqld IPv4 TCP 127.0.0.1:3306
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
Document Actions

Copyright © 2007-2015 Mario Theodoridis. All rights reserved. Content licensed under AFL.   Impressum   Datenschutz
Content from the underlying Plone CMS is © 2000-2009 by the Plone Foundation