With bash, there are lots of things that you can do. Some of them make GUIs look like interfaces for kids. Some others are not super useful, but intellectually fun.

Here's a random dump of things I've kept around as notes.

Who's using that?

To know if files or directories are being used by programs, two commands are super useful: fuser and lsof.


To know the PIDs of programs that have a certain file in their file descriptors, and the user names under which they are running:

fuser -u /var/log/mail.log

To show PIDs using any file under a mounted filesystem:

fuser -m /srv/

Create a screen session on a serial device, but only if nothing is already using it. Otherwise, try reconnecting to the current screen session:

if fuser -s /dev/ttyUSB2; then screen -x; else screen /dev/ttyUSB2 115200; fi


To list all files that are open by a certain process ID:

lsof -p 4194

To get all files open by a certain user:

lsof -u joejane

To see all established IPv4 connections from a certain process ID:

lsof -i 4 -a -p 31936

List all processes that have established an SSH connection:

lsof -i :22

Getting rid of all spaces in a tree of files

# this trick depends on bash features
# this command doesn't take any argument. it'll work on the current working
# directory and all of its subdirectories
nomorespace () { ls -1| while read i; do j=${i// /_}; if [ "$i" != "$j" ]; then mv "$i" "$j";fi; done; for i in $(find . -maxdepth 1 -type d -not -name "."); do pushd $i; nomorespace; popd; done; }

Switching file encoding

Sometimes it's useful to switch files that you get from the internet from one encoding to another that's more useful for you.

Transform flac files into ogg files

# This expects files to have track number at the start of the file followed by
# a dash like this:
# 01-Track_title.flac
for i in *.flac; do track=$(echo $i|sed -e 's/\([0-9][0-9]\).*/\1/'); title=$(basename $i .flac|sed -e 's/^[0-9]\+-//' -e 's/_/ /g'); flac -sdc $i | oggenc -a "Ali Farka Touré" -l "The river" -N "$track" -t "$title" -o $(basename $i .flac).ogg -; done

Transform m4a files into ogg files

# Same expectations for the filename as above
for i in *.m4a; do track=$(echo $i |sed -e 's/\([0-9][0-9]\).*/\1/'); title=$(basename $i .m4a|sed -e 's/^[0-9]\+-//' -e 's/_/ /g'); mplayer -quiet -vo null -vc dummy -ao pcm:waveheader:file="rawaudio.wav" "$i"; oggenc -a "Aphex twin" -l "Drukqs" -N "$track" -t "$title" -o ${track}-$(echo $title | sed -e 's/ /_/g').ogg rawaudio.wav; rm -f rawaudio.wav; done

Redefining builtin commands

This is rather more fun than useful, but I found it on a site that was instructing about what you can do when the infamous "rm -rf /" was run on a server and you need to salvage what you can from the remains of the explosion.

ls() {
  [ "x$1" == "-a" ] && ALL=".*"
  for i in $ALL *; echo $i; done

cat() {
  while read line; do echo $l; done < $1