kelan.io

Handy bash commands

I was touching up my bash profile this morning, and thought I’d share a few commands I find useful.

Local Locates: Search for filenames in a given directory tree

I think of these like slocate, but they work in just a specific directory, and don’t rely on the always-out-of-date-every-time-you-really-need-it slocate database.

I have two varieties. The first uses Spotlight, and is generally quicker, but less flexible in that it doesn’t allow for regexes.

llocate () {
    if [[ $# = 0 ]]; then
        echo
        echo "Search for filenames using Spotlight."
        echo
        echo "usage: $FUNCNAME MATCH_STR [START_DIR]"
        echo "    MATCH_STR    String (not regex) to match in the filename (not in full path)"
        echo "    START_DIR    The dir in which to look (default = CWD)"
        return 0
    elif [[ $# = 1 ]]; then
        startDir='.'
    else
        startDir="$2"
    fi
    mdfind -onlyin ${startDir} -name $1 | sort
}

The other uses find and grep, and is nice because it allows for regexes, and also works on Linux. You have to manually exclude scm dirs here, whereas Spotlight ignores hidden files and directories by default, so you don’t have to worry about that in llocate. However, if you are actually looking for hidden files, then you’ll need to use this command.

rlocate () {
    if [[ $# = 0 ]]; then
        echo
        echo "Search for filenames using find + grep (allowing regex)."
        echo
        echo "usage: $FUNCNAME PATTERN [START_DIR]"
        echo "    PATTERN      Regex to find (matching anywhere in the relative path)"
        echo "    START_DIR    The dir in which to look (default = CWD)"
        return 2
    elif [[ $# = 1 ]]; then
        startDir='.'
    else
        startDir="$2"
    fi
    find "${startDir}" \! -path "*/.svn/*" \! -path "*/.git/*" | `which grep` -i "$1"
}

Temporarily Disable Shell Commands

Sometimes you want to temporarily disable a command. For example, if you’re using a computer with an new version of svn, and are in a directory that has an old working copy, and you don’t want to accidentally do a svn status and have it upgrade the working-copy format (thus breaking it for your other computer that is stuck on an old version of svn). With this, you can simply do: disable svn, and then later do enable svn later to get it back.

disable () {
    alias $1="echo \"error: $1 is disabled\"; false" # return non-zero exit when it's called
    echo "$1 disabled"
}
enable () {
    unalias $1
    echo "$1 enabled"
}