Is it possible to create a command that is only available when in a current directory or any of it's subdirectories. For example, let's say I want to create a command/alias called cdtheme and I have the following directory structure


# PROJECTNAME and THEMENAME can be anything the rest of the structure will stay the same


Running cdtheme in the following directories would result in the following

~/code # error

~/code/projectA # cd to theme1
~/code/projectA/web # cd to theme1

~/code/projectB # cd to theme2

~/code/xyzproject # cd to randomthemename

cdtheme is just an example I would like to add more commands such as cdproject. My initial thought was to be able to add a file into a directory e.g projectB/.zshrc where I could define the custom command/alias/variables and have this picked up automatically.

Edit: Clarity and add context

  • By move, do you mean move a file or change drectory? Commented Mar 24, 2022 at 20:49
  • It's also unclear where exactly you want to move to - projectB or projectB/web/themes...
    – Panki
    Commented Mar 24, 2022 at 22:20
  • You can replace cd with a cd function in your ~/.bashrc that does a builtin cd "$@" , then looks around an sets up the alias OR unaliases it. Read man bash
    – waltinator
    Commented Mar 24, 2022 at 23:09
  • I've updated my question to make it clearer what I'm looking to achieve
    – mrmadhat
    Commented Mar 25, 2022 at 7:40

1 Answer 1


You can define and undefine aliases or functions in a chpwd hook.

function set_theme_dir {
  case $PWD/ in
    ~/code/projectA/) alias cdtheme='cd ~/code/projectA/web/themes/theme1';;
    ~/code/projectB/) alias cdtheme='cd ~/code/projectB/web/themes/theme2';;
    *) unalias cdtheme;;

But given your requirements I think it makes more sense for cdtheme to be always defined and to analyse the current directory when it runs.

function cdtheme {
  case $PWD/ in
    ~/code/projectA/) cd ~/code/projectA/web/themes/theme1;;
    ~/code/projectB/) cd ~/code/projectB/web/themes/theme2;;
    *) echo "Error: not inside a project tree" >&2; return 2;;

It's not clear whether theme directories are hard-coded or can be determined from the project, or how to tell what the project directory is. Here's an implementation of cdtheme that assumes that each project is its own Git worktree and that you want the first theme in lexicographic order.

function cdtheme {
  emulate -L zsh
  setopt err_return
  local root
  root=$(git rev-parse --show-toplevel)
  cd $root/web/themes/theme*([1])
  • or case $PWD/ in (~/dir/*)... to avoid the (|/*). Commented Mar 25, 2022 at 7:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .