That's a very insightful question, and it gets to the core of how shells manage their environment!
Aliases are not inherited by child shells primarily for reasons of efficiency, isolation, and predictability.
Here's a breakdown:
-
Efficiency: When you define an alias, it's essentially a text substitution managed directly by the shell that created it. Forcing every new child process to parse and maintain a list of aliases would add overhead, especially if many child processes are spawned. Shells are designed to be lightweight and fast for executing individual commands.
-
Isolation: Child processes are generally designed to be isolated from the specific configurations of their parent shell beyond what's critical for execution (environment variables). This ensures that a child process starts with a clean or predictable slate, rather than being influenced by every custom shortcut or setting a user might have defined in their interactive shell. If aliases were inherited, it could lead to unexpected behavior in scripts or programs that assume standard command names.
-
Predictability: Aliases are often very personal shortcuts or specific to an interactive session. For example,
alias ls='ls -lah --color=auto'. If a script were to runls, it might expect the default behavior, not the aliased version. By limiting aliases to the originating shell, the behavior of child processes and scripts becomes more predictable and less prone to side effects from user-defined aliases. -
How it works technically:
- Aliases are resolved by the shell before it tries to find the command executable. The shell processes your input, checks if it matches an alias, substitutes it, and then proceeds to execute the resulting command. This happens within the current shell instance.
- Environment variables are key-value pairs that are explicitly passed from a parent process to its child processes when the child process is created. The operating system's process management handles this inheritance.
In essence, aliases are a convenience feature of the interactive shell for the user, while environment variables are a standard mechanism for processes to communicate configuration information down their process tree.
You can observe a similar behavior with shell functions you define; they also aren't automatically inherited by child shells unless explicitly exported or sourced into the new shell.
This clear distinction between what gets inherited and what doesn't helps maintain order and control in the Linux environment.
Does this explanation help clarify why aliases behave this way?