←back to thread

700 points yen223 | 2 comments | | HN request time: 0.023s | source
Show context
tzs ◴[] No.42058339[source]
Here's a handy use I've found for mdfind.

Say you've got a directory that has scripts or data files related to some thing you do. For example I've got several scripts that I use when I scan books with my book scanner. I only need these when doing book scanning stuff so don't want to put them somewhere in $PATH. I want to be able to easily run them from scripts that aren't in that directory, but I don't want to hard code the path to that directory.

Solution: in the directory with the book scanning scripts I make a file named ID that contains a unique string. I currently use 16 byte random hex strings [1].

I have this script, named find-dir-by-ID, somewhere in $PATH:

  #!/bin/zsh
  ID=${1:?Must specific ID}
  IDSHA=`echo $ID | shasum | cut -d ' ' -f 1`
  mdfind $ID 2>/dev/null | grep /ID | while read F; do
      FSHA=`shasum $F | cut -d ' ' -f 1`
      if [ $IDSHA = $FSHA ]; then
          dirname $F
          exit 0
      fi
  done
  exit 1
If some script wants to use scripts from my book scanning script directory, it can do this:

  SCRIPT_DIR=`find-dir-by-ID 54f757919a5ede5961291bec27b15827`
  if [ ! -d $SCRIPT_DIR ]; then
    >&2 echo Cannot find book scanning scripts
    exit 1
  fi
and then SCRIPT_DIR has the full path to the scanning script directory.

The IDs do not have to be hex strings. If I'd thought about it more I probably would have made IDs look like this "book-scanning:54f757919a5ede59" or "arduino-tools:3b6b4f47bf803663".

[1] here's a script for that:

  #!/bin/sh
  N=${1:-8} # number of bytes
  xxd -g $N -c $N -p -l $N < /dev/urandom
replies(1): >>42058398 #
1. jeffhuys ◴[] No.42058398[source]
Why not just a directory with subdirectories by ID? No mdfind needed, no problems with just-created directories, no wait, etc
replies(1): >>42059692 #
2. tzs ◴[] No.42059692[source]
You mean something like having ~/well-known-stuff and under that having a 54f757919a5ede5961291bec27b15827 directory with the book scanning scripts and so on?

That could work fine, but generally the directories I've used this on are directories that I want to have somewhere else, and with a reasonable name. Usually the directories came first and various other things in fixed relative positions were using them, and then later I wanted to use them from elsewhere and added the ID.

I suppose ~/well-known/stuff/54f757919a5ede5961291bec27b15827 could by a symbolic link to the original.

The mdfind approach does have the advantage that if I reorganize things and move the directory it keeps working.