Skip to content

Instantly share code, notes, and snippets.

@leogama
Created September 13, 2017 00:28
Show Gist options
  • Save leogama/8929be9668689353b8f9a4a9c1766cda to your computer and use it in GitHub Desktop.
Save leogama/8929be9668689353b8f9a4a9c1766cda to your computer and use it in GitHub Desktop.
A decent and portable 'which' command for bash
function which {
local CMD=$1;
if alias $1 &>/dev/null; then
CMD=$(alias $1 | sed "s/^alias $1='\([^' ]*\).*$/\1/");
if [[ "$CMD" != $1 ]]; then
type $1;
which "$CMD"; # recursive call for nested aliases
return;
fi;
fi;
local FILE=$(type -P "$CMD");
# Add an * after the file that would be executed
type -a "$CMD" | sed '\|^'"$CMD"' is '"$FILE"'$|s|$| *|';
# If symlink, show the (likely) real file
[[ ! -L "$FILE" ]] && return;
local TARGET=$(command ls -l "$FILE");
echo "* symbolic link: $FILE -> ${TARGET#* -> }"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment