I have a command called up
(as a function in my bashrc) that allows me to easily go up to specified directories above the one I am in. The command works well, however adding bash tab completion would make it even more useful. I have written a completion script that identifies the directories in the current path and lists them for completion. The problem I am having is that whenever I change the directory, the completion script seems to not be reloaded, giving me the same results as if I were still in the previous directory. I was able to fix this for the up
command by adding exec bash
to the command function, however I am unsure whether I can do this for an arbitrary directory changing command. I suspect this could possibly be accomplished by just adding exec bash
for whenever the cd
command is run, but I am unsure what the best way to do this would be.
As an example:
If I open a terminal, I am in my home directory:
~$
If I type up <TAB><TAB>
, I get:
~$ up
username home
where username is my username on my pc. I then cd into dir1/dir2/
, and type up <TAB><TAB>
, and get:
~/dir1/dir2$ up
username home
again, even though I have changed my directory.
The code for my completion script and up script are as follows:
Completion script:
#/usr/bin/env bash
LS=$(echo $PWD)
LSARRAY=${LS//\// }
complete -W "$LSARRAY" up
Up command (in .bashrc)
LS=$(echo $PWD)
LSARRAY=(${LS//\// })
i=1
if [[ $LS == *$1/* ]]; then
FIND=$1
if [[ $1 == */* ]]; then
ARR=(${FIND//\// })
FIND=${ARR[${#ARR[@]}-1]}
fi
while [ "${LSARRAY[${#LSARRAY[@]}-$i]}" != "$FIND" ] && [ $i != ${#LSARRAY[@]} ]; do
cd ../
i=$(($i+1))
done
exec bash
else
echo "Did not find directory $1"
fi
cd
tab-completes to show only directories.