bash shell script alias expansion not working inside if statement

22 Views Asked by At

I wrote a simple script to test alias expansion but the output was not expected as below. I just would like to understand the reason or cause of this behavior.

#!/bin/bash

shopt -s expand_aliases

function echo_dbg()
{
    echo "Line# ($lineno): $*"
}

if true; then
    alias echo_dbg='lineno=$LINENO echo_dbg'
    echo_dbg "I want to print line#" # Don't know why this echo_dbg is not expanded 
fi

echo_dbg "I want to print line line#" # this echo_dbg is expanded correctly

My terminal output:

Line# (): I want to print line#
Line# (15): I want to print line line#

However, if I moved alias definition above fi statement, two echo_dbg's worked as expected.

#!/bin/bash

shopt -s expand_aliases

function echo_dbg()
{
    echo "Line# ($lineno): $*"
}

alias echo_dbg='lineno=$LINENO echo_dbg'

if true; then
    echo_dbg "I want to print line#"
fi

echo_dbg "I want to print line line#"

My terminal output:

Line# (13): I want to print line#
Line# (16): I want to print line line#
0

There are 0 best solutions below