How do I find the path to a program in Terminal?

You can use type and which to determine what a certain command in bash is, and, if it's an application, where it resides.

$ type type
type is a shell builtin
$ type cd
cd is a shell builtin
$ type ls
ls is aliased to `ls --color=auto'
$ type -P ls
/Users/danielbeck/bin/ls
$ which which
/usr/bin/which
$ which ls
/Users/danielbeck/bin/ls

The commands which and type -P only work for programs on your PATH, of course, but you won't be able to run others by just typing their command name anyway.


If you're looking for a simple way to determine where an OS X (GUI) application bundle is installed (as used e.g. by the open command), you can execute the following short AppleScript from the command line:

$ osascript -e 'tell application "System Events" to POSIX path of (file of process "Safari" as alias)'
/Applications/Safari.app

This requires that the program in question (Safari in the example) is running.


This is the method I currently to locate the Firefox application directory in OSX and Linux. Should be easy to adopt to another application. Tested on OSX 10.7, Ubuntu 12.04, Debian Jessie

#!/bin/bash

# Array of possible Firefox application names.
appnames=("IceWeasel" "Firefox")    # "Firefox" "IceWeasel" "etc

#
# Calls lsregister -dump and parses the output for "/Firefox.app", etc.
# Returns the very first result found.
#
function get_osx_ffdir()
{
    # OSX Array of possible lsregister command locations
    # I'm only aware of this one currently
    lsregs=("/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister")

    for i in "${lsregs[@]}"; do
        for j in ${appnames[@]}; do
            if [ -f $i ]; then
                # Some logic to parse the output from lsregister
                ffdir=$($i -dump |grep -E "/$j.app$" |cut -d'/' -f2- |head -1)
                ffdir="/$ffdir"
                return 0
            fi
        done
    done
    return 1
}

#
# Uses "which" and "readlink" to locate firefox on Linux, etc
#
function get_ffdir()
{
    for i in "${appnames[@]}"; do
        # Convert "Firefox" to "firefox", etc
        lower=$(echo "$i" |tr '[:upper:]' '[:lower:]')
        # Readlink uses the symlink to find the actual install location
        # will need to be removed for non-symlinked applications
        exec=$(readlink -f "$(which $lower)")
        # Assume the binary's parent folder is the actual application location
        ffdir=$(echo "$exec" |rev |cut -d'/' -f2- |rev)
        if [ -f "$ffdir" ]; then
            return 0
        fi
    done
    return 1

}


echo "Searching for Firefox..."

ffdir=""
if [[ "$OSTYPE" == "darwin"* ]]; then
    # Mac OSX
    get_osx_ffdir
else
    # Linux, etc
    get_ffdir
fi

echo "Found application here: $ffdir"

# TODO: Process failures, i.e. "$ffdir" == "" or "$?" != "0", etc

If the program is running, you can call

ps -ef | grep PROGRAM

Tags:

Macos

Terminal