Is it normal that:

```bash
if true
then
alias my_test='echo test'
my_test
fi
```

returns

```
my_test: command not found
```

?
Feb 6, 12:20am

Great question, Benjamin! The behavior you're observing is completely normal in Bash, and here's why:

Why the alias doesn't work inside the if block

  • Aliases are not expanded in non-interactive shells by default. When you run a script or a block of code (like inside an if statement), Bash does not expand aliases unless you explicitly enable it with shopt -s expand_aliases.

  • Aliases are shell-specific. Even if you enable alias expansion, the alias my_test is only available in the current shell instance where it was defined. If the if block is run in a subshell (which is not the case here, but it's a common point of confusion), the alias would not persist outside of it.

How to fix it

If you want to use an alias inside a script or a block, you need to enable alias expansion at the start of your script or block:

bash
shopt -s expand_aliases if true then alias my_test='echo test' my_test fi

Or, more simply, use a function instead of an alias for scripts:

bash
if true then my_test() { echo test; } my_test fi

Functions are expanded in non-interactive shells and are generally more reliable for scripting.

Summary Table

Alias vs Function in Bash
Expansion
Needs shopt -s expand_aliases
Always works
Scope
Shell-specific
Shell-specific
Script-friendly
❌ No
✅ Yes

Would you like to explore more about Bash scripting or aliases?

Feb 6, 12:20am

This Chat is read-only. Login to resume chatting.

shopt -s expand_aliases if true then alias my_test='echo test' my_test fi
if true then my_test() { echo test; } my_test fi