Why doesn't my Bash script recognize aliases?

In my ~/.bashrc file reside two definitions:

  1. commandA, which is an alias to a longer path
  2. commandB, which is an alias to a Bash script

I want to process the same file with these two commands, so I wrote the following Bash script:


for file in "$@"
    commandA $file
    commandB $file

Even after logging out of my session and logging back in, Bash prompts me with command not found errors for both commands when I run this script.

What am I doing wrong?

Asked By: Zaid


If you look into the bash manpage you find:

Aliases are not expanded when the
shell is not interactive, unless the
expand_aliases shell option is set
using shopt (see the description of

So put a

shopt -s expand_aliases

in your script.

Make sure to source your aliases file after setting this in your script.

shopt -s expand_aliases
source ~/.bash_aliases
Answered By: ddeimeke

First of all, as ddeimeke said, aliases by default are not expanded in non-interactive shells.

Second, .bashrc is not read by non-interactive shells unless you set the BASH_ENV environment variable.

But most importantly: don’t do that! Please? One day you will move that script somewhere where the necessary aliases are not set and it will break again.

Instead set and use variables as shortcuts in your script:



for file in "$@"
    $CMDA "$file"
    $CMDB "$file"
Answered By: user601

Aliases can’t be exported so they’re not available in shell scripts in which they aren’t defined. In other words, if you define them in ~/.bashrc they’re not available to your_script.sh (unless you source ~/.bashrc in the script, which I wouldn’t recommend but there are ways to do this properly).

However, functions can be exported and would be available to shell scripts that are run from an environment in which they are defined. This can be done by placing this in your bashrc:

    echo "Hello World!"
export -f foo

As the Bash manual says, “For almost every purpose, shell functions are preferred over aliases.”

Answered By: Dennis Williamson
[cmd line] > bash -i [your script's file path]

The i is for interactive and sources your bash profile for you.

Answered By: user65576

You can also use . before your script. Run it as:

. /path/to/your/script.sh

You can check for this condition on your bash script as follows:

if [[ $- == *i* ]]
    echo "running on interactive mode. aliases will work!"
Answered By: Tono Nam
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.