bashshellposixalias

Are there circumstances in which bash seems to violate the order of precedence for aliases?


I found the order of precedence described here but if and only if bash is instructed to source a script after the alias is given in .bashrc does the alias-function get used by the sourced script.

E.g.:

function save_cd(){
  cd "$@" 
  echo "$(pwd)" > dummy file 
  echo "$(pwd)"
};
alias cd="save cd";
source 'script-that-calls-cd-in-it'

When I tried sourcing the script that calls cd before declaring cd to be an alias the alias was not"expanded" in the shell environment if I'm using expanded properly here. Instead subsequent calls to sourced_script_defined_function used the cd built-in rather than my alias/function or in my case.. nothing was echoed.


Solution

  • Aliases are expanded at parse time. When you define an alias after defining a function intended to call it, that function has already been parsed, so it's too late for the alias to have any effect. Move the alias definition above the function definition, and then it would change the behavior of that function.


    More to the point, in your current use case you don't need any alias at all. Consider:

    cd() {
      command cd "$@" || return  # with no arguments, returns $?
      printf '%s\n' "$PWD" >dummyfile
      printf '%s\n' "$PWD" >&2
      return 0  # report success if cd succeeded, even if the last printf did not
    }
    

    Notes about changes made here: