How to change current working directory inside command_not_found_handle

I am trying to write an undefined descriptor in Bash that does the following:

  • If there is $ 1 and it is a directory, cdinto it.
  • If $ 1 exists inside the user directory $DEV_DIR, `cd into it.
  • If the previous conditions do not apply, complete the failure.

I now have something like this:

export DEV_DIR=/Users/federico/programacion/

function command_not_found_handle () {
    if [ -d $1 ]; then          # the dir exists in '.'
        cd $1
    else
        to=$DEV_DIR$1
        if [ -d $to ]; then
            cd $to
            echo `pwd`
        else
            echo "${1}: command not found"
        fi
    fi
}

And although it works (the command echo pwdprints the expected directory), the directory in the actual shell does not change.

I got the impression that since this is a function inside mine .bashrc, the shell will not fork, and I could do it cd, but apparently this does not work. Any advice on how to solve this problem would be appreciated.

+3
3

, , fork() , , command_not_found_handle .

+2

, , , , autocd:

shopt -s autocd

man bash:

autocd - , ,                       , cd com-                       MAND. .

, , , command_not_found_handle .

+1

It will not change the directives if you run this program as a script in the main shell, because it creates a sub-shell when it is executed. If you use a script in the current shell, then it will have the desired effect.

~/wbailey> source command_not_found.sh

However, I think the following result will achieve the same result:

wesbailey@feynman:~/code_katas> cd xxx 2> /dev/null || cd ..; pwd
/Users/wesbailey

just replace ".." with your env var with a specific directory and create an alias in your .bashrc file.

0
source

All Articles