6

I would like to declare an alias (in my .bash_profile) that will use the content (value) of a variable when the alias is used, not when it is defined. E.g.,

alias goSomeWhere="cd $BASE/somewhere"

$BASE is not set when the alias is defined, only when is it used. But, because $BASE is evaluated when the alias is defined (at login time), the goSomeWhere alias is interpreted as cd /somewhere.

How can I delay the evaluation of the variable until the alias is executed?

iXô
  • 363

2 Answers2

7

Replace both " by ' or prefix $ with a \.

Cyrus
  • 5,751
4

alias is a builtin, not a keyword that could make Bash interpret the rest of the line in a different way than it normally does this. And normally double-quoted (or unquoted) variables are expanded by the shell before the command (or the builtin) is invoked. This happens in your case. Note the expansion is not limited to the part after =. I mean you can do this:

var1=alias
var2='foo=bar'
"$var1" "$var2"

and it will effectively create an alias that turns foo into bar. In your definition you want $BASE to be single-quoted, so it's not expanded.

Any alias replaces text with text. It's purely textual. As you want goSomeWhere to be replaced with literal

cd $BASE/somewhere

Wait. No, you don't want the above, you want the below:

cd "$BASE/somewhere"

Your definition should be:

alias goSomeWhere='cd "$BASE/somewhere"'

See Parameter expansion (variable expansion) and quotes within quotes. The variable is single-quoted when the alias is defined, but properly double-quoted after the alias is expanded (which happens every time you use it).