1

Why does this only print arg out once?

$ alias test="echo $1 $1 $1"
$ test arg
arg

This is on GNU bash, version 4.2.25(1)-release (x86_64-pc-linux-gnu).

0

2 Answers 2

2

List aliases with alias command after you defined that alias and you will clearly understand it:

alias test="echo $1 $1 $1"
alias

Output:

alias test='echo   '

It simply expands to a string with variables only which were defined at execution time. So this for example works (Vvariable MY_VAR is defined):

MY_VAR="foo"
alias test="echo $MY_VAR $MY_VAR $MY_VAR"
alias

Output:

alias test='echo  foo foo foo'

You can replace it with function

function test() {
    echo $1 $1 $1
}
1
  • 1
    Variables can be expanded at run time if aliases are defined with single quotes alias est='echo 1${1} var${var}'. The problem then is $1 is still not populated as the OP expects. The function is the solution.
    – Matt
    Commented Sep 11, 2013 at 8:20
1

I doubt if alias supports $1,$2,... Its help keeps silence on that.

So I think that your command test arg is expanded like echo $1 $1 $1 arg. Where $1 is empty and you get your result.

1 more example:

$ alias test='echo $1 $1 $1'
$ test arg1 arg2
arg1 arg2

In the above example the alias test=... get's executed and the net effect is we're let with an alias to the command echo. We can see this effect when we run the command test arg1 arg2. All we're doing is running echo and passing it the strings arg1 and arg2.

$ echo arg1 arg2
8
  • Your example doesn't show anything other than "echo $1 $1 $1" is aliased as test=echo. And you're test arg1 arg2 is really doing echo arg1 arg2.
    – slm
    Commented Sep 11, 2013 at 8:16
  • Thats exactly what I'm saying. Why minus?
    – sshilovsky
    Commented Sep 11, 2013 at 8:17
  • It's not showing anything. The $1's are meaning less in an alias. I'm not sure what you're trying to say in your answer, it's reading a bit fractured to me. Keep word smithing it and I'll gladly undo it.
    – slm
    Commented Sep 11, 2013 at 8:20
  • You say my post would be better without that example?
    – sshilovsky
    Commented Sep 11, 2013 at 8:22
  • Yeah that example isn't helping your answer that much. If you leave it I'd add a couple of sentences explaining it a bit. Not trying to nit pick just trying to help you.
    – slm
    Commented Sep 11, 2013 at 8:27

Not the answer you're looking for? Browse other questions tagged .