Bash – Is there some way to make alias expansion work inside if…fi on Bash

aliasbash

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".

Best Answer

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 "$@"; }
Related Question