0

I am getting the following result:

alias foo="echo hello`$1`"
foo bar         #outputs `hello bar` with an unwanted space

the desired output is hellobar

--- Edit: ---

I have found a workaround for the above for now:

foo(){ echo hello$1 }
foo bar      #outputs hellobar
Oliver Williams
  • 5,966
  • 7
  • 36
  • 78
  • Or better use `printf 'hello%s\n' "$1"` – anubhava Mar 22 '23 at 10:54
  • Your report is not accurate; it should print `something: command not found` on standard error, where `something` is the _current_ value of `$1` in your interactive shell. If `$1` is unset, it will work without an error, but define an alias whose value is `echo hello` – tripleee Mar 23 '23 at 05:45

1 Answers1

2

Yes, that is as expected. Alias does not use arguments.

So, what happens is:

alias foo="echo hello`$1`"

This defines foo as an alias of

echo hello`$1`

$1 of your current shell is probably empty. The backticks around it will execute $1 as command at the time you define the alias and use the output. And executing nothing will result in nothing. So the alias effectively becomes echo hello.

Then you do:

test bar         

Replacing test with foo (it is probably what you actually did), results therefore in

echo hello bar

and that is where your space comes from.

If you want to create an alias-like thing that accepts arguments, look at functions.

foo2(){
    echo "Hello$1"
}

foo2 bar

which is what you wanted.

Ljm Dullaart
  • 4,273
  • 2
  • 14
  • 31
  • Actually, `foo` is simply `echo hello`, and `$1` gets evaluated as a command. If it is unset, nothing happens. If it is a random string, you get an error message. If it is a random string which happens to also be a valid command, you get the output of that command after `hello` in the alias, without a space. The lack of quoting in the alias definition might complicate matters further. – tripleee Mar 23 '23 at 05:46
  • That is what "executing nothing will result in nothing" was ment to mean. I'l elaborate a bit on that. – Ljm Dullaart Mar 23 '23 at 07:35
  • The crucial correction is that this happens when the alias is defined, not when it is used. – tripleee Mar 23 '23 at 07:41