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.
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:
cd() {
with no function
avoids getting into bash-only habits (function
is a bash extension for compatibility with ancient ksh releases, and not part of the POSIX sh standard).command cd
prevents recursion.$PWD
instead of $(pwd)
is far faster, avoiding the overhead of forking a subshell to run command substitution.|| return
causes the function to abort with a nonzero exit status if cd
fails.printf
instead of echo
avoids the bugs discussed in Why is printf better than echo?.>&2
to redirect to stderr prevents your attempts to log from being redirected into pipes, files, or other locations where they would both be invisible to the user and throw off other processing.