I spend a lot of time on the command line.

And I have got a lot of common directories I tend to use. One of them is a bit special. It contains my daily work or projects I work on over several weeks at a time. I usually visit those directories regularly. Since typing (even with a tab) takes some time, I have aliases for the most common directories.

But I do not want to make an alias every time I change something in that directory, right?

So there is this nice little function in my .bashrc, that automatically reads the sub-directories and creates aliases by itself:

# Automatic alias creation
# Reads subfolders and creates aliases
# $1 = path
# $2 = pattern [optional]
shopt -s expand_aliases
function dir_alias {
  directory="$1"
  if [ "${!2}" == '' ]; then
    pattern=${2}
  else
    pattern=''
  fi
  if [ -e "${directory}" ]; then
    subdirectories=$(find "$directory" -maxdepth 1 -type d )
    for subdir_line in ${subdirectories//\\n/ } # While loop does not work, runs in a subshell
    do
       # Get the directory name
       directory_name=$(basename $subdir_line)
       alias_name="gtd${directory_name}"

       if [ "${pattern}" != '' ]; then # No match set
         if [[ "${directory_name}" =~ ${pattern} ]]; then

           # Remove leading dates if available
           number_pattern="^([0-9]{4,8})-.*"
           if [[ "${directory_name}" =~ $number_pattern ]]; then
             arr_name=(${directory_name/-/ })
             directory_name=${arr_name[1]}
             alias_name="gtd${directory_name}"
           fi

           # Create alias
           alias $alias_name="cd $subdir_line"

         fi
       else

         # Create alias
         alias $alias_name="cd $subdir_line"

       fi

    done
  fi
}

# Generating general aliases base on the file structure
dir_alias /data/git
dir_alias /data/oc/oc/dokumenter/work  '^([0-9]+)-.*'

The last to lines will create aliases for two different scenarios:

  1. All git repositories that I store in /data/git. A repository with the name suppertool will be available with the alias gtdsuppertool.
  2. All directories in the sub-directory work, that match a pattern. In this case I usually create my projects with yyyy-project. This creates an alias like gtdproject.