0

I'm trying to do something like this. But it's not working.

$ alias setroot="export ROOT=$1; export PATH=$ROOT/bin:$PATH"
$ setroot /path/to/root
bash: export: `/path/to/root': not a valid identifier

Can someone point out, what is going wrong here? To clarify, I need ROOT also in my environment.

1 Answers1

0

Alias is literally replaced and $1 is empty, because your interactive shell was started with no arguments and all variables $1, $ROOT and $PATH are expanded when defining your alias, because you used double quotes. So:

setroot /path/to/root

does:

export ROOT=; export PATH=<content_of_ROOT>/bin:<content_of_PATH> /path/to/root

The second argument to second export is invalid identifier - /path/to/root contains /, and variables can't contain /. The content_of_ROOT is the value of ROOT when defining alias, not upon using it.

Use a function. Check your scripts with shellcheck.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • But it works fine in case of `alias setroot="export ROOT=$1; cd $ROOT"` – Partha Bera Oct 18 '21 at 14:35
  • 1
    In that case it does `alias setroot='export ROOT=; cd '` and `cd` just changed directory and it set's `ROOT` variable to empty. It does not work as you expect and `$1` does not have the value you expect it to have. Use ex. `( set -x ; setroot semething )` in command line debug your scripts. Research difference between single and double quotes. – KamilCuk Oct 18 '21 at 14:40
  • Using a function just does the job and is probably the best option too. Thanks @KamilCuk – Partha Bera Oct 18 '21 at 14:45
  • To my knowledge, I always thought Aliases could not receive Arguments. You have to work around that with a function. – Steve Kline Oct 18 '21 at 17:11