2

I have defined an alias like so:

alias X="path/to/program"

and I have a function defined like this:

doX() { X -flag "$1"; }

I put these in my .bashrc file, and when I open bash, I get a syntax error near unexpected token '-flag'. At this point, the alias has been set, but the function has not, due to this error. If I run

doX() { X -flag "$1"; }

at this point, it works. I have tried putting this into a file and sourcing it after I set the alias in the .bashrc file, but it is giving me the same results.

How can I fix this? Is there a way to define the alias AND the function in the .bashrc so that they are both set when I open bash?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Abraham
  • 219
  • 1
  • 12
  • 1
    Is there a reason you don't just set your path instead of using an alias? – Paul Hodges Oct 15 '18 at 20:54
  • I wanted to do something like (cd Desktop; path/to/program), I wasn't sure if I could do this in a path – Abraham Oct 15 '18 at 21:20
  • You can very much do that in a function; you **can't** do it reliably in an alias (`alias foo='(cd Desktop; path/to/program)'` will behave badly when it you tell it `foo bar` and it tries to run `(cd Desktop; path/to/program) bar` instead of `(cd Desktop; path/to/program bar)`). You can fix that in a function by passing `"$@"` in (only) the exact location where your arguments should be substituted (and as an aside, always use `&&`, not `;`, after a `cd` so you don't run your program in the wrong directory if it fails). – Charles Duffy Oct 15 '18 at 23:50

1 Answers1

0

Aliases are not usually available in scripts. If you want to have a function use an alias, consider making the alias itself a function:

X() { path/to/program "$@"; }
doX() { X -flag "$1"; }
Fengyang Wang
  • 11,901
  • 2
  • 38
  • 67
  • If the "path" includes subcommands, can I do something like this? `X() { (cd Desktop; path/to/program) "$@"; } ` Also, what does the "$@" do? Should I use "$*" instead? – Abraham Oct 15 '18 at 21:17
  • 3
    @Abraham See https://stackoverflow.com/questions/2761723/what-is-the-difference-between-and-in-shell-scripts – Barmar Oct 15 '18 at 21:26
  • @Abraham You might be able to use `(cd Desktop; path/to/program "$@")`; the arguments must be inside the subshell. – Fengyang Wang Oct 15 '18 at 22:51
  • 2
    Better, `(cd Desktop && exec path/to/program "$@")` -- the `&&` makes sure you don't try to run the program if the `cd` fails, and the `exec` consumes the subshell, mooting the performance cost of having created it. – Charles Duffy Oct 15 '18 at 23:51