Sogartar
Sogartar

Reputation: 2175

Bash: declaration of an alias to be used in a single lined multiple commands

I would like to do something like

alias myls=ls && myls

This gives me an error

bash: myls: command not found

Strangely, a subsequent

myls

in the same session would be recognized.

Do you know how to declare alias, that is used in the same command sequence?

Upvotes: 1

Views: 67

Answers (3)

pynexj
pynexj

Reputation: 20688

According to the bash manual:

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. This behavior is also an issue when functions are executed. Aliases are expanded when a function definition is read, not when the function is executed, because a function definition is itself a compound command. As a consequence, aliases defined in a function are not available until after that function is executed. To be safe, always put alias definitions on a separate line, and do not use alias in compound commands.

For almost every purpose, aliases are superseded by shell functions.

Upvotes: 2

Leon
Leon

Reputation: 32474

anubhava has already provided a better answer, but if for some reason you don't want to use a function instead of an alias then you can do

alias myls=ls && eval myls

Note, however, that usage of eval introduces an extra level of expansion, which may result in unexpected behaviour for more complex commands:

$ echo "A    B"
A    B
$ eval echo "A    B"
A B
$ echo '$SHELL'
$SHELL
$ eval echo '$SHELL'
/bin/bash

Upvotes: 1

anubhava
anubhava

Reputation: 785068

alias has to be used on a separate line so even this won't work:

alias myls=ls; myls

This will result in -bash: myls: command not found error.

However, you can use function and use it on same line:

myls() { ls "$@"; } && myls

Upvotes: 1

Related Questions