wting / autojump

A cd command that learns - easily navigate directories from the command line
Other
16.06k stars 702 forks source link

Autojump Does Not Work Inside of Bash Script #666

Closed mowestusa closed 1 year ago

mowestusa commented 1 year ago

I'm a newbie when it comes to bash scripting, so there could be a simple fix.

I have a bash variable that holds the directory name of the working directory where the bash script cd into during while the script is running. Since I tend to start this script from my home folder, when I exit the script I would like to remain in that working directory.

However, when I put the command at the end of my bash_script

j $DIR

I get the error message = line 62: j: command not found

If I change the command to autojump $DIR I don't get the error "command not found" but it doesn't jump to the directory either.

It seems like this should work, because if I create a bash variable in the terminal just at the command line the following occurs:

DIR=directory_name
autojump $DIR
/$HOME/directory_name #it simply prints out the correct path
j $DIR
/$HOME/directory_name #it prints it out in red and jumps to the correct directory that matches the path

I'm doing this currently on WSL 2 in Ubuntu 22.04, running bash, but I would think this would be the same behavior on all my systems.

mowestusa commented 1 year ago

After doing additional research and discovering that aliases don't work in bash scripts either, I thought the solution would be to add the following into the script at the beginning before cd is invoked.

export PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND ;} history -a"
source /usr/share/autojump/autojump.bash
autojump -v
j -v

I believe the above code does work, and autojump is working within the script, because I get the result on the commandline, and I don't get the warnings about command not found.

autojump v22.5.1
autojump v22.5.1

After I create the variable holding the directory name and after cd is invoked during the running of the script, at the very end of the script I once again had the code:

j $DIR pwd

I noticed in the CLI after the script ran I had the following: . #period was in red indicating that autojump jumped to the directory it was already in from the previous cd command. /$HOME/directory_name/ #pwd returned the desired working directory.

When the script exited I was dumped back into the origin directory where I started the script. So I believe the problem is not with autojump, but instead the problem is with the default behavior of bash which once again I can only over come with source bash_script or executing a new bash session at the end of the script.

Sorry for my confusion. I really enjoy the bash shell even with its limitations, and autojump makes using the CLI a delight. Thanks for all the hard work on this amazing program. I'm marking this closed because it was my misunderstanding not an issue with autojump.