How to Access Aliases Defined in .bash_profile/.bashrc from Functions
The aim of this page is to explain alias behavior in Bash functions based on the particular example of a script trying to call a shell alias. My particular alias was cc
which is by default a clang compiler.
1 min readMay 6, 2024
type -a cc
cc is aliased to `${INF_PATH}/consul_getter/consul_getter.sh'
cc is /usr/bin/cc
- Alias Not Working in Function? An alias defined in
.bash_profile
wasn't working as expected within a function in the same file. - Reason: By default, function environments don't inherit alias definitions from the main shell session.
Solutions
- Use the full path to the script the alias points to within the function.
- Enable alias expansion (
shopt -s expand_aliases
) inside the function, but be cautious of potential side effects.
shopt expand_aliases
: This Bash builtin allows enabling/disabling alias expansion within the shell or functions.
Setting expand_aliases
:
- In a function: Affects only that specific function.
- In a shell configuration file (
.bashrc
,.zshrc
): Applies to the entire shell session (my way, use with care)