Yair
Yair

Reputation: 518

Can't use alias within backticks inside bash script

I have the following script:

for i in 1 2 3 
do
 alias echo${i}="echo ${i}"
 alias aliastest${i}="echo aliastest `echo${i}`"
done

after executing it, I'd expect to have 3 aliases in the names aliastest1, aliastest2, aliastest3.

However I'm getting:

./test.sh: line 5: echo1: command not found
./test.sh: line 5: echo2: command not found
./test.sh: line 5: echo3: command not found

Note that when trying to execute echo1, echo2, echo3 from command line, it does work as expected.

What am I doing wrong?

Upvotes: 1

Views: 229

Answers (1)

chepner
chepner

Reputation: 531165

Alias expansion is only enabled for interactive shells by default. You would need to add

shopt -s expand_aliases

to the beginning of the script.

It's likely that whatever alias you want to define, you should probably be defining as a shell function instead.

Upvotes: 2

Related Questions