0

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#
Tony Su
  • 57
  • 6
  • 1
    An alias defined within a complete command does not take effect until the shell is done processing that command. There is a similar question here: https://stackoverflow.com/q/65266726 – oguz ismail Mar 10 '21 at 08:49
  • Got it, thanks. solved my puzzle. – Tony Su Mar 10 '21 at 09:09

0 Answers0