Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Check this script:

#!/bin/bash
if true;then
    alias WeirdTest='uptime';shopt -s expand_aliases
    WeirdTest
fi
WeirdTest

The first time WeirdTest is executed it says "command not found".

share|improve this question

1 Answer 1

up vote 9 down vote accepted

This is a limitation of bash. Quoting the manual:

The rules concerning the definition and use of aliases are somewhat confusing.

Bash expands aliases when it reads a command. A command, in this sense, consists of complete commands (the whole if … fi block is one compound command) and complete lines (so if you wrote … fi; WeirdTest rather than put a newline after fi, the second occurrence of WierdTest wouldn't be expanded either). In your script, when the if command is being read, the WeirdTest alias doesn't exist yet.

A possible workaround is to define a function:

if …; then
  WeirdTest () { uptime; }
  WeirdTest
fi
WeirdTest

If you wanted to use an alias so that it could call an external command by the same name, you can do that with a function by adding command before it.

WeirdTest () { command WeirdTest --extra-option "$@"; }
share|improve this answer
    
I have several if..fi defining the (same) alias inside of it (actually thru a sourced huge script); so following your "function tip", I defined a function with the same alias identifier before all the ifs (and so before all source loading) but this way: function WeirdTest() { eval WeirdTest "$@"; } so I used eval, and it is now working! I think it did not ended on an endless recursive loop because WeirdTest got redefined into an alias; I believe tho eval should be avoided, but I am still not convinced why, by all I read about, I think I need to research more.. –  Aquarius Power Jul 2 at 0:27
1  
@AquariusPower I have a hard time imagining a context where this function would make sense, or why you'd want to use eval. –  Gilles Jul 2 at 0:30
    
that's the problem, I must fill this gap between your knowledge and mine :), I used eval just because it worked. –  Aquarius Power Jul 2 at 0:43
    
anyone interested about "do not use eval" read the last paragraph here; and to finally get scared go here –  Aquarius Power Jul 2 at 2:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.