Recursive type

This is some of my more obscure shell scripting. This gets information from the type builtin in (say) Bash to display everything at once. So, rather than:

$ type -a k1
k1 is aliased to `k9 %1'
$ type -a k9
k9 is aliased to `kill -9'
$ type -a kill
kill is a shell builtin
kill is /bin/kill

(You know, a whole three commands to run in this case…. :-))

We could go with:

$ type k1

*** Evaluating : k1

k1 is aliased to `k9 %1'

*** Evaluating : k9

k9 is aliased to `kill -9'

*** Evaluating : kill

kill is a shell builtin

There's some ANSI color coding (well, bold text) in play there too. Thanks to Todd for the tip about tput, that's much more convenient than trying to copy the escape character around (can be quite tricky in some ways).

The following ("self-documented", I believe it's called ;-)) code can be included in .bashrc. Note that there are some limitations and it could probably be cleaner. It's mostly for fun anyway. :-) Or download the script.

function echo_bold                                                             
{                                                                              
  echo "$(tput bold)${@}$(tput sgr0)"                                          
}                                                                              

function th
{          
  P="$@"   

  ABORT=0
  MAYBE_FILE=0

  while [ $ABORT -ne 1 ]
  do                    
    echo_bold           
    echo_bold "*** Evaluating : $P"
    echo_bold                      

    T=`builtin type -t "$P"`

    SHOW=1

    OLD_P="$P"

    case $T in
      'function' | 'file' | 'builtin' | 'keyword' )
        ABORT=1

        if [ "$T" == "file" ]
        then
          MAYBE_FILE=1
          SHOW=0
        fi

        ;;
      'alias' )
        EXPR=`builtin type "$P" | sed 's/^[^\`]*\`//' | sed 's/.\$//'`
        ALIAS=`echo "$EXPR" | awk '{print \$1}'`

        if [ "$ALIAS" == "$P" ]
        then
          ABORT=1
          MAYBE_FILE=1
          SHOW=0
        fi

        P="$ALIAS"
        ;;
      '' )
        echo "... nonexistent!"

        SHOW=0
        ABORT=1
        ;;
      * )
        echo_bold
        echo_bold "*** ERROR: unrecognised type: $T"
        echo_bold

        SHOW=0
        ABORT=1
        ;;
    esac

    if [ $SHOW -eq 1 ]
    then
      builtin type "$OLD_P"
    fi
  done

  if [ $MAYBE_FILE -eq 1 ]
  then
    builtin type -a "$P"
  fi
}

alias type='th'
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License