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.

Pavol Kutaj

--

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

  1. Use the full path to the script the alias points to within the function.
  2. 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)

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com