Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does variable expansion within an alias work "as intended" in only one of these cases?

This question was inspired in part by this one.

alias foo='ls -1 $1'
foo /etc

displays the contents of /etc, one item per line.

ls -1 /etc | tail

displays the last ten items in /etc.

But

alias foo='ls -1 $1 | tail'
foo /etc

displays: tail: error reading `/etc': Is a directory

like image 469
brec Avatar asked Jan 04 '12 21:01

brec


People also ask

What is the difference between Alias and variable?

Variables replace their content wherever they are used. Aliases act as actual commands, or rather the prefix of one.

What is Alias expansion?

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.


2 Answers

I have found variable expansion in aliases to be flaky, and not recommended:
http://www.gnu.org/software/bash/manual/bashref.html#Aliases

Use a function instead: function foo() { ls -1 $1; }

like image 138
speeves Avatar answered Sep 24 '22 01:09

speeves


Aliases done this way will only expand from the set of parameters:

$ alias foo='ls -1 $1 | tail'
$ foo .
# Type Esc-C-e: this expands aliases/globs/environment variables...
# ... And the result of the expansion is:
$ ls -1  | tail .
# $1 has disappeared
$ set bar  # set $1...
$ foo . # again, Esc-C-e
$ ls -1 bar | tail .
like image 27
fge Avatar answered Sep 23 '22 01:09

fge