0

have a weird problem..... Im configuring my arch setup and one of my aliases isnt working.....

alias es='echo $SCRIPTDEST/$1'

For some reason it prints a space between $SCRIPTDEST/ and $1, ruining everything. How do I fix this?

Also $SCRIPTDEST is just the location of all my scripts.

Also, here is a screenshots of any relevant outputs I believe would help. If anything else is needed let me know.

Picture removed as not suitable for all viewers. Contains mild horror. Please replace with text.

ctrl-alt-delor
  • 27,473
  • 9
  • 58
  • 102
Delupara
  • 303
  • 2
  • 3
  • 9
  • Aliases don't take arguments, so `$1` isn't doing what you think it is; [use a function instead](https://unix.stackexchange.com/questions/30925/in-bash-when-to-alias-when-to-script-and-when-to-write-a-function). This is at least partly a duplicate of ["How to pass parameters to an alias?"](https://unix.stackexchange.com/questions/3773/how-to-pass-parameters-to-an-alias) and ["Using arguments in the replacement text of an alias"](https://unix.stackexchange.com/questions/331301/using-arguments-in-the-replacement-text-of-an-alias) – Gordon Davisson Feb 15 '20 at 04:35
  • Would be if I had noticed that it didn't even took arguments. Would of probably never even asked because my search would of been completely different and probably would of led to my answer. Sometimes even googlefu can't help if you're looking for the completely wrong thing... – Delupara Feb 15 '20 at 08:27

1 Answers1

2

There is this question In Bash, when to alias, when to script, and when to write a function? and it explains a lot. Your question can be addressed specifically though.

Most important thing is: an alias in Bash replaces one string with another string before the line is processed further. There is no logic; there is no separate $1 specific to the alias. There's only string replacement.

Your alias definition:

alias es='echo $SCRIPTDEST/$1'

Now if you run

es foo

then es will be replaced by echo $SCRIPTDEST/$1. Everything that follows stays, including the space before foo. The result is like

echo $SCRIPTDEST/$1 foo

and it is then evaluated further. $1 here is what the shell thinks it is, it has nothing to do with the alias. From your description it looks $1 expands to an empty string. The variable is not quoted, it's another bug.

I guess you thought foo becomes $1 in the context of the alias. If so, when you wrote "a space between $SCRIPTDEST/ and $1" you meant what is in fact "a space between $SCRIPTDEST/$1 and foo". This is the very space you typed between es and foo.

A function takes arguments and refers to them as $1, $2 etc. The following function does what I think you wanted from your alias:

unalias es
es () {
   printf '%s\n' "$SCRIPTDEST/$1"
}

Additional fixes: quoting, echo.

Kamil Maciorowski
  • 19,242
  • 1
  • 50
  • 94