Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash: unable to set and use alias in the same line

I would expect the second line to say foo instead of command not found:

$ alias foo="echo bac" ; foo;
-bash: foo: command not found
$ foo
bac
$

Why won't the second line say foo? Tested with the following shells, same behavior:

  • bash 3.2.5
  • zsh 5.0.8
  • dash 0.5.9
  • busybox 1.25.0
like image 588
Motiejus Jakštys Avatar asked Jul 22 '16 12:07

Motiejus Jakštys


People also ask

Can aliases be used within bash shell scripts?

BASH Alias is a shortcut to run commands using some mapping. It is a way to create some shortcut commands for repetitive and multiple tasks. We create an alias in a BASH environment in specified files. We can also incorporate BASH functions, variables, etc to make the Alias more programmatic and flexible.

How do I override an alias?

The backslash escape character before a shell command disables and override any shell aliases.

How do I bypass alias in Linux?

Use a “\” (backslash) before the command to run it without the alias. The backslash escape character can be used before a shell command to override any aliases. For example if rm was made into an alias for rm -i then typing “rm” would actually run rm -i.


1 Answers

The behaviour you're seeing is described in the Bash Reference Manual (emphasis mine):

The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at least one complete line of input before executing any of the commands on that line. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the alias definition on that line are not affected by the new alias.

Presumably the other shells also behave in this way.

like image 114
Tom Fenech Avatar answered Oct 02 '22 03:10

Tom Fenech