3

I want to cd to some directory within /long/path/name/. I would like a function cd2 that

  • Takes an argument
  • cds to /long/path/name/$argument
  • And autocompletes from cd2 <tab><tab> as if I had run cd /long/path/name/; cd <tab><tab>

It is the third requirement that I am having trouble with. I can get a function to autocomplete only the subdirectories of /long/path/name/, but I cannot continue tabbing to get subdirectories of that subdirectory.

I would like to autocomplete as if I had typed cd in /long/path/name/. The ideal would be to easily adapt _cd to do the job, but that may not be possible.

I have been using the code below, but I have to admit that I am new to bash autocomplete and do not fully understand the _cdFromDir syntax.

function cd2() {
    cd /long/path/name/$@ ;
}

_cdFromDir() {

  local cur prev opts
  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  prev="${COMP_WORDS[COMP_CWORD-1]}"
  opts=$(ls /long/path/name/)
  COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
  return 0

}

complete -F _cdFromDir cd2
1
  • well written question. I don't have an answer to this but GOOD JOB! Commented Jun 22, 2023 at 17:49

2 Answers 2

1

On my ubuntu system, complete -p cd shows:

complete -o nospace -F _cd cd

To do what you seem to want to do, I can define:

cd2top='/long/path/name'
cd2(){ builtin cd "${@:-"$cd2top"}"; }
_cd2(){ [[ $PWD =~ ^"$cd2top" ]] || cd "$cd2top"; _cd; }
complete -o nospace -F _cd2 cd2
1
  • This solved it, thank you! On my system, the complete statement is "complete -F _cd2 cd2" but otherwise works perfectly.
    – ASV
    Commented Jun 22, 2023 at 21:36
0

jhnc's answer is excellent and provides 95% of the work. There were a couple small issues I fixed:

  • After running the command, cd - did not take me back to the directory where I ran the command from. (This is because of the cd in the autocomplete function.)
  • The command did not autocomplete within the directory where it takes you. So if it takes me to /a/ and I am in /a/b/c/ and want to get to /a/d/e/, I could not get autocomplete.
cd2() {
  builtin cd "${@:-"/long/path/name/"}"

  # Change directory back to original PWD if autocomplete changed it
  if [[ -e ~/cd2TempFile.txt ]]; then
    read origDir < ~/cd2TempFile.txt
    OLDPWD=$origDir
    rm ~/cd2TempFile.txt
  fi
}

_cd2(){

  if [[ ! $PWD =~ ^"/long/path/name$" ]]; then
    echo $PWD > ~/cd2TempFile.txt
    cd "/long/path/name/";
  fi

  _cd;
}

complete -F _cd2 cd2

You must log in to answer this question.

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