0

Say I have this bash function:

cd(){
 builtin cd "$@"
 echo "do my own thing"
}

the problem is that if I override cd in another place, only 1 override will count, any other override will be overwritten by the latest sourced function!

Is there a way to have multiple cd functions and for them to all be called?

I am thinking something like this:

alias prev_cd="cd";

cd(){
   prev_cd  
   echo "do my own thing"
}

but I doubt that's quite right..the problem with the prev_cd solution is that it will result in an infinite loop. Where prev_cd calls my cd function, and vice versa. I only want prev_cd to be defined as cd definitions outside of this file..

One trick I can use is I can find the file that the cd function is located in using:

shopt -s extdebug
declare -F cd
shopt -u extdebug

if I have already overridden the cd command, I can call unset -f cd?

It looks like RVM (Ruby Version Manager) overrides cd:

cd 14 /Users/alexamil/.rvm/scripts/cd

so I don't want to mess up previous overrides of cd..so I only want to override cd if I don't mess up the previous overrides...

3
  • @Vlastimil do you understand the question? is it not clear? Commented May 2, 2018 at 5:00
  • if the question is not clear, perhaps this makes it clearer: github.com/rvm/rvm/issues/4373 Commented May 2, 2018 at 5:03
  • Specifically on RVM, its definition of cd is to call __zsh_like_cd cd and that function __zsh_like_cd will be in your environment... So maybe just using that in your own redefinition of cd might be OK... It relies on RVM not changing the rules, but might be good enough... But see below for a more general answer.
    – filbranden
    Commented May 2, 2018 at 5:27

1 Answer 1

2

You can copy the body of the cd definition into a new function with the prev_cd name. Use declare -f cd to get that definition and then eval to redefine that.

definition_prev_cd="prev_$(declare -f cd)"
eval "${definition_prev_cd}"
unset definition_prev_cd  # clean up, no reason to leave this string around

cd () {
   prev_cd "$@"
   echo "do my own thing"
}

You could add some checks or create a generic function to copy arbitrary functions, but this should be enough to get you to solve the problem you described...

4
  • thanks, can I use export -f prev_cd here? Commented May 2, 2018 at 5:29
  • if I try that, I get: bash: export: prev_cd: not a function Commented May 2, 2018 at 5:33
  • yeah looks like if this is sourced more than once, then declare -f cd will point to the new definition, so I have to check if it's been sourced already. Commented May 2, 2018 at 5:38
  • Yes, you need to repeat this procedure if cd (from RVM) gets redefined... That will overwrite your definition.
    – filbranden
    Commented May 2, 2018 at 5:48

You must log in to answer this question.

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